0

I'm trying to change a global variable in multiple defines

here's my code:

x = 4

def thing_1():
 global x
 x += 1
 return x

def thing_2():
 x += 4
 return x

print(x)

thing_1()

print(x)

thing_2()

print(x)

I was expecting x to change each time... instead I got the error: "UnboundLocalError: local variable 'x' referenced before assignment"

1 Answers1

0

The problem is at the function thing_2() , the x there is local and you haven't define it before you increased its number.

if you want to change the global variable you must add global x at the beginning

def thing_2():
    global x
    x += 4
    return x