Scope of Variable Local and Global in Python

In this class, we discuss the scope of variable local and global in python.

For Complete YouTube Video: Click Here

Local and Global Variable

The reader should have basics on functions. Click here.

Take an example and understand local and global variables, then go to the variable scope.

# local and global variables
i=1
def f():
    j=20
    print(j+i)
def f1():
    k=25
    print(k+i)
f()
f1()
print(i)

From the above example variable, i is called the global variable.

The variable j defined in the function f is called the local variable.

What is the difference between local and global variables?

The global variable i in our example can be used and modified anywhere in our python script.

So the scope of the global variable is a complete python script.

We can use the local variable j only in the function f.

So the scope of the local variable is within the function.

From the above program, variable k is local to function f1.

The variable i, which is global in our example, is used in functions f and f1. We used the variable i out of the functions also.

Examples

Let’s take some examples to understand the concept of local and global variable scope better. 

i=1
def f():
    i=20
    j=20
    print(i+j)
f()
print(i)

Variable i is defined as both local and global in the above program.

This situation if we use the variable i inside the function. The function will check for local variables.

If the variable i not found in local variables. Then function checks the variable i in the global variables list.

Print(i+j) will display 40. because the variable i value is taken from local variable space.

Print (i) statement written outside the function. This statement will take variable i from global variable space.

Suppose the same variable name is used. The local variable is hiding the global variable.

Example 2:

i=1
def f():
    i=20
    l=20
    print(i+l)
f()
print(i)
print(l)

From the program mentioned above.

The variable l is local to the function. Suppose we try to access the variable l outside the function. We get an error message.