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.

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

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

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

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:


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

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

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


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
total = func2(4,5)