Python variable scope

Variable scope means. after declaring or creating a variable, accessible area of that variable. Basically, 2 types of scope are available in Python, local scope and global scope. This section will cover all types of variable scope and their use.


Objectives

  • Local scope

  • Global scope


Python Local scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

Code

# Local variable example
def print_my_name():
    name = "Touhid Mia"
    print("My name is " + name)


# Call the function
print_my_name()

# Call the local variable
print(name)

Output

My name is Touhid Mia
    print(name)
NameError: name 'name' is not defined

Process finished with exit code 1

Note : You are seeing that in output there is an error called NameError: name 'name' is not defined, because local variable not accessible outside the function.


Python Global scope

In general variables declare inside a function not accessible outside from that function because that variable is Local variable. But sometimes you may need to share variable to multiple function so the technique of share variable across multiple function called global scope.

Code

# Global variable example

name = "Touhid Mia"  # Global variable


def print_my_name():
    print("Function: My name is " + name)


# Call the function
print_my_name()

# Call the global variable
print("Outside : " + name)

Output

Function: My name is Touhid Mia
Outside : Touhid Mia

Process finished with exit code 0

Note : You are seeing that in output has no error because Global variable can access from inside of function and outside a function as well.

Python Global variable inside function

Code

# Global variable example
def print_my_name():
    global my_name
    my_name = "Touhid Mia"
    print("My name is " + my_name)


# Call the function
print_my_name()

# Call the local (global) variable
print(my_name)

Output

My name is Touhid Mia
Touhid Mia

Process finished with exit code 0

Note : You are seeing that in output has no error, but the same code earlier show error, but why? In this code we have added global my_name inside the function that’s why the variable now behave like Global variable


Python variable scope video tutorial