python in global scope

#python variable reference sequence: The current scope of local variables -> enclosing scope Variables -> variable current global module -> Python built-in variables. 

'' ' 
A = 30 declared as a global variable 
a = 20 to test () function is a local variable, and the variable of the same name without modification 
can use the local variables, references to the order of: the current scope of local variables 

' '' 
A = 30 
DEF Test (): 
    A = 20 is 
    Print (A) 
Test () 
Print (A)

Print results

20

30

'' ' 
A = 30 The first line defines a global variable 
in test1 () function in the program because "If the internal variable or function has the same name as a global variable references to external functions, and there are modifications to this variable. Python so that it will is a local variable, 
and because the function is not a definition and assignment, so given 
a = a + 20, a is a local variable, 
'' ' 
a = 30 
DEF test1 (): 
    a = a + 20 is 
    Print (a) 
test1 () 
Print (A)

Error message:

a=a+20

UnboundLocalError: local variable 'a' referenced before assignment

'' ' 
Declared global variables local to global variables to be modified, it must first declare the need for global variables in the local: ' 

'' 
A = 30 
DEF test2 (): 
    Global A 
    A + A = 20 is 
    Print (A) 
test2 () 
Print (A)

Print results

50

50

 

Guess you like

Origin www.cnblogs.com/tallme/p/11300807.html