Hi All,
Steadily trying to learning Python basics…I’m trying to create a score variable here…but I get an “unresolved reference” error in the ‘choice_of_path’ function.
Can someone explain why? I refer to ‘Score’ in the top of the code?
Thanks! I assume this is something simple I don’t quite get! - Matt
name = input("What is your name? ")
score = 0
#Greeting
def greet(name):
print(“Hey there!”)
print("Great to see you, " + name)
choice1 = input(question)
if choice1 in ['R', 'r', 'right', 'Right', 'RIGHT']:
print (right_answer)
score += 1
elif choice1 in ['L', 'l', 'left', 'Left', 'LEFT']:
print (left_answer)
else:
print("You didn't choose the right thing! Try again")
choice_of_path(“You are in a field with lots of grain, which way do you go?”, “You got swallowed”, “You won the gold!”)
print(score)
choice_of_path(“You are now in a basketball stadium, which way do you go?”, “You scored a big goal”, “You lost game!”)
UnboundLocalError: local variable ‘score’ referenced before assignment
Please copy and paste error messages exactly, don’t paraphrase them.
To fix that error, put this line:
global score
as the first line of your choice_of_path function.
The reason for the error is that inside a function variables are
considered “local variables” that only exist inside the function. You
are trying to add 1 to a local variable that doesn’t exist yet! To tell
the Python interpreter that you want to use the global variable that
exists outside the function, you need that line global score at the
start of the function.
choice1 = input(question)
global score
if choice1 in ['R', 'r', 'right', 'Right', 'RIGHT']:
print (right_answer)
score += 1
print(score)
elif choice1 in ['L', 'l', 'left', 'Left', 'LEMaFT']:
print (left_answer)
else:
print("You didn't choose the right thing! Try again")
choice_of_path(“You are in a field with lots of grain, which way do you go?”, “You got swallowed”, “You won the gold!”)
choice_of_path(“You are now in a basketball stadium, which way do you go?”, “You scored a big goal”, “You lost game!”)