Reputation: 233
I have my code as below.
def test():
print num1
print num
num += 10
if __name__ == '__main__':
num = 0
num1 = 3
test()
When executing the above python code I get the following output.
3
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<stdin>", line 2, in test
UnboundLocalError: local variable 'num' referenced before assignment
I do not know why particularly num is not available in test method. It is very weird for me and i did not face this yet before.
Note: I am using python 2.7.
Upvotes: 0
Views: 1424
Reputation: 7823
Since you're assigning to num
inside the test
function, python considers it to be a local variable. This is why it complains that you are referencing to a local variable before assigning it.
You can fix this by explicitly declaring num
to be global:
def test():
global num
print num1
print num
num += 10
if __name__ == '__main__':
num = 0
num1 = 3
test()
Upvotes: 1
Reputation: 531035
num
appears in an assignment statement inside the definition of the test
. This makes num
a local variable. Since scope determination is made at compile time, num
is a local variable even in the print
statement that precedes the assignment. At that time, num
has no value, resulting in the error. You need to declare num
as global if you want to access the global value. num1
does not have this problem, since you never try to assign to it.
def test():
global num
print num1
print num
num += 10
Upvotes: 1