Python:如何正确修改已经使用过的全局变量

时间:2017-08-29 19:51:46

标签: python if-statement global

我正在用Python进行初学者练习。

代码要求提供姓名和年龄。如果年龄高于100岁,我想将age_goal修改为150.任何超过150岁的年龄都不会被接受。

current_year = 2017
age_goal = 100
question = "Would you like to know which year you will turn " + str(age_goal) + " years old? (Yes/No): "

user = input("What is your name?: ")
print("Hello, " + user + ".")

age = input("How old are you, " + user + "?: ")  

if int(age) > 100 and int(age) < 150:
    global age_goal
    print("Whoa, that's old!")
    age_goal = 150
elif int(age) >= 150:
    print("No one's THAT old...")
    age = input("How old are you, " + user + "?: ")
else:
    print("You are " + str(age) + " years old.")

calc = age_goal - int(age) + current_year

response = input(question)

while response != "Yes" and response != "No":
    print("Answer not accepted, try again: ")
    response = input(question)
if response == "No":
    print("That's no fun. Goodbye.")
else:
    if response == "Yes":
        print("You will be" + str(age_goal) + " years old in " + str(calc) + "!")

下面列出了有问题的if语句。

if int(age) > 100 and int(age) < 150:
    global age_goal
    print("Whoa, that's old!")
    age_goal = 150

现在它说&#34; name&#39; age_goal&#39;在全局声明和#34;之前使用,我明白这意味着什么以及它为什么会抛出这个错误,但是我不知道如何组织代码来接受修改后的全局,从那时起,而不是试图使其适用于整个代码。

1 个答案:

答案 0 :(得分:2)

如果您已经在全局命名空间中,则不需要使用global。这意味着当您想要修改函数内的全局变量时。