Python scope of variables with examples – Local vs Gloabl

In this tutorial, we are going to learn about the scope of variables in Python with examples.

The scope of variables refers to where they can be accessed and used inside the program.
There are 2 types in scope of variables:

  • Local variables
  • Global variables

Local variables

Local variables in Python are the variables that are declared inside the function. And the variables that can only be used within the function itself. Once the function has finished executing, we cannot access that variable again.

Example for local variable:

def my_function():
    a = 100
    print(a)
my_function()

In the above example, we defined a variable inside the function so it is a local variable. And we get the output.

Output:
100
def my_function():
    a = 100
    print(a)
my_function()
print(a)

In the above example, we defined a variable inside the function and if we call the variable after the execution of the function we get an error because it’s a local variable the variable will be within the function itself.

Output:
NameError : name 'a' is not defined

Global variables

Global variables in Python are the variables that are declared outside the function. And we can access the variables both inside and outside the function. Once the function has finished executing also we can access that variable again.

Example for global variables:

a = 100
def my function():
    a = a * 2
    print(a)
my function()
    

In the above example, we defined a variable outside the function so it is a global variable. And we get the output.

Output:
200
a = 100 
def my function():
    a = a * 2
    print(a)
my function()
print(a)

In the above example, we defined a variable outside the function and if we call the variable after the execution of function also we get the output because it’s a global variable the variable will be within and out of the function.

Output:
200
100

Leave a Reply

Your email address will not be published. Required fields are marked *