0

This is a random code which is similar to my own project code. When i run it it says UnboundLocalError: local variable 'score' referenced before assignment. Can anyone fix it.

score = 0

def Random_Thing():
    Random_Text = input("Random Text")
    if Random_Text == "Hello":
        score = score + 1
        print(score)

def Random_Thing_2():
    Random_Text_2 = input("Random Text 2")
    if Random_Text_2 == "Hello2":
        score = score + 1
        print(score)

Random_Thing()
Random_Thing_2()
print(score)

1 Answers1

0

When you define score = 0 at the top, it is in the global scope for the file. By default, functions have only read access to global variables. You cannot change them. Therefore print(score) would work inside a function. But score=score+1 would not.

If you want to change global variable(s) from inside a function, do global var1, var2... at the begining of the function. For your code, you need to do

def Random_Thing():
    global score
    #your code

def Random_Thing_2():
    global score
    #your code
Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31