Variables scope defines where the variable is accessible in the program. We can think of this as the lifetime of a variable. Outside this scope, the variable no longer exist.

Variable scope represents the duration of the code where the variable exists. Python removes unnecessary variables when we no longer need them in order to save memory in our system. This process is sometimes called garbage collection.

Local Variable Scope

All the variables defined inside the body of a function are called local variables.

1def sample_fn():
2    name = "Jessica" # we cannot use this outside the function body
3    print(name)
4
5sample_fn()
6print(name)

This produces an error because local variable name is not available outside the sample_fn function on line 6.

$ python main.py
Jessica
NameError: name 'name' is not defined

Global Scope Variable

Global variables are variables defined outside any function body and they are available anywhere in the code.

1name = "Andrew" # global variable
2
3def sample_fn():
4    name = "Jessica" # Local variable: we cannot use this outside the function body
5    print(name)
6
7sample_fn()
8print(name)

In this case, because we have defined name variable outside any function at the top level. This is called Global variable and this is accessible anywhere in the program even at line 8 outside the sample_fn function.

Output:

Jessica
Andrew

We can also access the global variables inside the function. If we modify the global variable after using global keyword, it will actually modify the variable value even outside the function body.

1name = "Andrew" # global variable
2
3def sample_fn():
4    global name
5    name = "Jessica"
6    print(name)
7
8sample_fn()
9print(name)

This code block modifies global name variable and hence this prints the same name two times.

Output:

Jessica
Jessica

We should avoid modifying global variables inside a function to avoid confusion. This can result in bugs which can be difficult to trace.

Block Level Variables

Python doesn’t have block level scope. In other languages, the variable defined inside the block is not accessible outside the code block. However, in below example, the variable defined on line 3 is surprisingly accessible on line 5 and similarly for variable inside while block is also accessible outside it.

 1def sample_fun():
 2    if True:
 3        result = "Block variable"
 4    # Outside if block
 5    print(result)
 6    
 7    i = 0
 8    while i < 1:
 9        i += 1
10        another_result = "Another block variable"
11    # Outside while block
12    print(another_result)
13
14sample_fun()

Output:

Block variable
Another block variable