简体   繁体   中英

Python weird variable scope issue

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.

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM