python in a global statement

The global statement

If you need to modify global variables within a function, use the global statement. If there is such a code global eggs at the top of the function, it tells Python, "In this function, eggs refers to the global variable, so do not create a local variable with this name."

def spa():
	global eggs
	eggs = 'spa'
eggs = 'global'
spa()
print(egg)

Output: spa
because the top eggs in Spa () is declared as global, it is the time when eggs 'spa' assigned, the assignment occurs on a global scope spa. Do not create a local spa variables.
There are four rules to distinguish one variable is in the local scope or global scope:

  1. If the variable is used (that is, outside all functions) in global scope, it is always global variables.
  2. If a function, there is a global statement for the variable, it is a global variable.
  3. Otherwise, if the variable is used in the function assignment, it is a local variable.
  4. However, if the variable is not used in the assignment statement, it is a global variable.
def spam(): 
	global eggs
	eggs = 'spam' # this is the global
def bacon():
    eggs = 'bacon' # this is a local
def ham():
    print(eggs) # this is the global
eggs = 42 # this is the global
spam()
print(eggs)
Published 340 original articles · won praise 128 · views 20000 +

Guess you like

Origin blog.csdn.net/king9666/article/details/104096135