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

Python: How to properly modify a global variable that's already been used

我正在 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

现在它说 "name 'age_goal' is used prior to global declaration",我明白这意味着什么以及它抛出该错误的原因,但我不知道如何组织代码以从那时起接受修改后的全局,而不是尝试使其适用于整个代码。

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