Global and Local variables


There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.

global-local-variable
A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists only in block 3.

Local variables

Local variables can only be reached in their scope.
The example below has two local variables: x and y.

def sum(x,y):
    sum = x + y
    return sum
 
print(sum(8,6))

The variables x and y can only be used inside the function sum, they don’t exist outside of the function.
Local variables cannot be used outside of their scope, this line will not work:

print(x)

Global variables

A global variable can be used anywhere in the code.
In the example below we define a global variable z

z = 10
 
def afunction():
    global z
    print(z)
 
afunction()
print(z)

The global variable z can be used all throughout the program, inside functions or outside.
A global variable can modified inside a function and change for the entire program:

z = 10
 
def afunction():
    global z
    z = 9
 
afunction()
print(z)

After calling afunction(), the global variable is changed for the entire program.

Exercise

Local and global variables can be used together in the same program.
Try to determine the output of this program:

z = 10
 
def func1():
    global z
    z = 3
 
def func2(x,y):
    global z
    return x+y+z
 
func1()
total = func2(4,5)
print(total)