global and nonlocal variable in Python
Most of us are already familiar with global variables in Python. If we declare those variables in a module, the functions inside that module (can read python file or .py file) can access the variable. For example, check the code below : 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 determi...