mardi 29 août 2017

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

I am doing a beginner's exercise in Python.

The code asks for a name and age. If the age is higher than 100, I want to modify age_goal to 150. Any age entered above 150 will not be accepted.

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) + "!")

The if statement in question is listed below.

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

Right now it says "name 'age_goal' is used prior to global declaration", and I understand what that means and why it's throwing that error, but I don't know how to organize the code to accept the modified global from that point on, versus trying to make it work for the code as a whole.

Aucun commentaire:

Enregistrer un commentaire