Global, Local, and Nonlocal Variables
A global variable is a variable declared outside of the function or in the global scope. This means that a global variable can be accessed inside or outside the function.
You can access global variables within functions (READ ONLY), but if you want to change them - declare 'global':
x = 5
y = 10
def change_x():
global x
x += 10
return x
def change_x_y():
global x, y
x += 20
y += 20
return x, y
print(x, y) # 5 10
print(change_x()) # 15
print(x, y) # 15 10
print(*change_x_y()) # 35 30
print(x, y) # 35 30
print(*change_x_y()) example we used unpacking (*). This made it possible to print variables not in a tuple — 35 30 instead of (35, 30).
Nonlocal variables refer to all those variables that are declared within nested functions. Variables can be neither in the local nor the global scope. Use the nonlocal keyword to create a nonlocal variable. Let's compare functions without and with using this keyword: