The scope of a variable is the part of the program where the variable can be accessed or used. There are two main types of scopes in Python: global scope and local scope

Global Scope

Global scope is the scope that covers the entire program . Variables that are defined outside any function or class are in the global scope . They can be accessed or used anywhere in the program, unless they are shadowed by a local variable with the same name. 

For example, in this program:

x = 10 # global variable

def print_x():

    print(x) # access global variable

def change_x():

    x = 20 # local variable

    print(x) # access local variable

print_x() # prints 10

change_x() # prints 20

print(x) # prints 10

x is a global variable that can be accessed or used in any function or statement. However, in the function change_x, there is a local variable x that shadows the global variable x. This means that inside the function change_x, x refers to the local variable, not the global variable.

Local Scope

Local scope is the scope that covers a specific function or class. Variables that are defined inside a function or class are in the local scope. They can only be accessed or used within that function or class, and they are destroyed when the function or class ends. 

For example, in this program:

def add_two_numbers(a, b): # define a function with two parameters

    result = a + b # local variable

    return result # return local variable

z = add_two_numbers(10, 20) # call the function and assign its return value to z

print(z) # print z

print(result) # error: result is not defined

result is a local variable that is defined and used inside the function add_two_numbers. It can only be accessed or used within that function, and it is destroyed when the function ends. Therefore, trying to print result outside the function will cause an error.

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.