简体   繁体   中英

Python Local and Global Variables

def spam():
    print(eggs)
    eggs = 13

eggs = 12
spam()

This gives the error:

UnboundLocalError: local variable 'eggs' referenced before assignment

But this does not:

def spam():
    print(eggs)


eggs = 12
spam()

Why?

In the first example, when you do eggs = 13 , the function tries to find the definition within it's scope, assuming it as a local variable,and since no such variable is defined within the function, local variable 'eggs' referenced before assignment. exception is thrown.

In the second example, since no such assignment is present, eggs is taken from the global scope, which is eggs=12 , hence no such exception is thrown here

To resolve this issue, you need to assign a local variable eggs within the function. Here only the local variable eggs is referenced to and changed, the global variable eggs is the same.

In [40]: def spam(): 
    ...:     eggs = 12 
    ...:     print(eggs) 
    ...:     eggs = 13 
    ...:     print(eggs) 
    ...:  
    ...: eggs = 12 
    ...: spam() 
    ...: print(eggs)                                                                                                                                                                
12
13
12

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