Python global and nonlocal variable in Python
x = 5
def myfnc():
print(“inside myfnc”, x)
def myfnc2():
print(“inside myfnc2”, x)
myfnc2()
myfnc()
It will print :
inside myfnc 5
inside myfnc2 5
If you change your code like this :
x = 5
def myfnc():
print(“inside myfnc”, x)
def myfnc2():
print(“inside myfnc2”, x)
x = 10
print(“x = “, x)
myfnc2()
myfnc()
You will get an error :
File “program.py”, line 6, in myfnc2
print(“inside myfnc2”, x)
UnboundLocalError: local variable ‘x’ referenced before assignment
The moment you wrote x = 10, Python assume that x is a local variable, and inside the print function, it is giving this error. Because local variables are determined at compile time (from official doc : “local variables are already determined statically”). You can get rid of the error, if you declare x as global.
x = 5
def myfnc():
print(“inside myfnc”, x)
def myfnc2():
global x
print(“inside myfnc2”, x)
x = 10
print(“x = “, x)
myfnc2()
myfnc()
Now you can run the program again. It won’t throw any error. What if we code like this now?
x = 5
def myfnc():
print(“inside myfnc”, x)
y = 10
def myfnc2():
global x
print(“inside myfnc2”, x, y)
x = 10
print(“x = “, x)
myfnc2()
myfnc()