UnBoundLocalError in Python while printing global variable

Question:

Why is this code giving ‘UnboundLocalError: local variable ‘num1′ referenced before assignment’ error?

num1=50
def func():
   print(num1)
   num1=100
func()
Asked By: Saurav.Kumar

||

Answers:

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()
Answered By: cs95
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.