Search notes:

Python: statement global

The following simple Python declares a variable (num) and a function (printNum) that simply prints the value of num:
num = 42

def printNum():
    print(num)

printNum()
Github repository about-Python, path: /statements/global/1-print-var.py
Now, if a function contains an assignment to the variable, the variable is considered to be local to the function and hides the global variable with the same name.
Because (the local) num is not assigned a value at the time of the print() function, an UnboundLocalError exception (with the explanation local variable 'num' referenced before assignment) is thrown:
num = 42

def printNumAndIncrement(i):
    print(num)
    num = num + i

printNumAndIncrement(57)
printNumAndIncrement( 1)
Github repository about-Python, path: /statements/global/2-assign-to-var.py
In order to print the value of num, use the global statement needs to be used:
num = 42

def printNumAndIncrement(i):
    global num
    print(num)
    num = num + i

printNumAndIncrement(57)
printNumAndIncrement( 1)
Github repository about-Python, path: /statements/global/3-use-global.py
Its noteworthy to point out that variables within a function that are only referenced, but not assigned to, are implicitly global.

See also

Using the global statement in a module.
The nonlocal statement
statements

Index