First, local and global variables
Local variables: the variables in the function body refers to the definition of the scope of the internal function body only
Global Variables: variable refers vitro function definition, the scope is the whole code segment
Therefore, in vivo function can directly access the global variables can not access the local variables in the function vitro
Second, modify global variables in the function body
When the function body to modify global variables, Python automatically generates a name as a local variable with global variable, so as to achieve protection of global variables (not change the value of a global variable in the operation of the function body), but can be use global keyword in a local variable, global variable modifications , as follows
1 x = 1 2 def function(): 3 x = 5 4 print(x) 5 6 >>> function() 7 5 8 >>> print(x) 9 1
global keyword
1 x = 1 2 def function(): 3 globals x 4 x = 5 5 print(x) 6 7 function() 8 5 9 >>> x 10 5