Why is this code giving ‘UnboundLocalError: local variable ‘num1′ referenced before assignment’ error?
num1=50 def func(): print(num1) num1=100 func()
Another gotcha! of python. This is because of hoisting and variable shadowing. If you have a local and global variable with the same name in a particular scope, the local variable will shadow the global one. Furthermore, declarations are hoisted to the top of their scope.
So your original code will look something like this:
num1=50 def func(): num1 = ... # no value assigned print(num1) num1=100 func()
Now, if you try to print
num1 without having assigned any value to it, it throws
UnboundLocalError since you have not bound any value to the variable at the time you are trying to dereference it.
To fix this, you need to add the
global keyword to signify that
num1 is a global variable and not local.
num1=50 def func(): global num1 print(num1) num1=100 func()