簡體   English   中英

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

現在它說“名稱'age_goal'在全局聲明之前被使用”,我理解這意味着什么以及為什么會引發該錯誤,但是從那時起我不知道如何組織代碼來接受修改后的全局,而不是嘗試使其整體上適用於代碼。

如果您已經在全局名稱空間中,則無需使用global 這是當您要在函數內部修改全局變量時使用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM