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:
- If the variable is used (that is, outside all functions) in global scope, it is always global variables.
- If a function, there is a global statement for the variable, it is a global variable.
- Otherwise, if the variable is used in the function assignment, it is a local variable.
- 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)