为什么苹果不增加?

时间:2016-11-06 19:15:27

标签: python-3.x numbers

我正在尝试制作我发现的这个小游戏,并且出于某种原因,当我在“你想要摘苹果吗?”上键入“Y”时。无论我尝试什么,IT都会保持在1。这是我的代码:

import time
global choice
global gold
global apples
apples = 0
gold = 0

def begin():
    apples = 0
    gold = 0
    print ("Let's go!")
    if gold > 99:
        print ("You've won the game!")
        play = input ("Do you want to play again? Please answer Y/N.")
        if play == "Y":
            begin()
        if play == "N":
            print ("Okay, bye then.")
    pick = input ("Do you want to pick an apple Y/N?")
    if pick == "Y":
        print ("You pick an apple")
        apples=apples+1
        apples = 1
        print ("You currently have,",apples," apples")
        begin ()
    if pick == "N":
        sell = input("Do you want to sell your apples Y/N?")
        if sell ==  "Y":
            gold
            apples
            print ("You currently have,",apples,"apples")
            print("You have sold your apples")
            gold=apples*10
            print ("Your gold is now:",gold)
            begin()
            start()

print ("Hello and welcome!")
name = input("What's your name?")
print ("Welcome, "+name+"!")
print ("The goal of this game is to collect apples")
print ("After you have collected these applaes, you sell them.")
choice = input("Do you want to play? Type Y/N.")
if choice == "Y":
    begin()
if choice == "N":
    print ("Okay, bye then.")

如果有人能帮我解决这个问题,我们将不胜感激。我只是一个初学者,所以不要太苛刻。对不起,如果这个问题很明显,我刚刚开始。

2 个答案:

答案 0 :(得分:0)

行后

apples = apples + 1

你有一行

apples = 1

将苹果重置为1,使其显示您只有1个苹果。

答案 1 :(得分:0)

您的代码顶层有一堆global语句。那些什么都不做。如果您要使用全局变量,则需要将global语句放在使用变量的函数中,以告诉Python使用该名称的全局变量而不是使用局部变量。

尝试:

apples = 0 # don't repeat these lines inside the function
gold = 0   # (unless you want the variables to get reset each time you call it)

def begin():
    global gold # move the global statements inside the function
    global apples

    # ...

choice变量似乎没有在begin函数中使用,因此您不需要global语句。

正如Dobellyo指出的那样,你在函数中apples的任务中也有一些混乱的逻辑。您需要决定何时增加现有值以及何时要分配固定值。一个接一个地做两者通常是没有意义的。