Scope in Python | Variable Scope, Lifetime

Using a function defines the concept of scope in Python.

If we define a variable inside a function or pass a value to a function’s parameter, the value of that variable is only really accessible within that function. This is called scope.

In other words, the scope is the region of a program where we can access a particular identifier or variable. This is called scope of variable or simply variable scope.

Variables declared inside a program may not be accessible at all locations of that program. It depends on the where we have declared a variable in a program.

Most variables that we define in Python are local in scope to their own function or class. Consider the following example code below.

Example 1:

# Python program demonstrates the variable's local scope.
def localScope():
    name = 'John'
    print(name) # Accessible.

# Main program.
print(name) # Not accessible because the variable name is undefined here.
localScope() # calling function.
Output:
      print(name) # Not accessible because the variable name is undefined here.
      NameError: name 'name' is not defined

In the above example, the variable name defined inside the function will be accessible within that entire function. Therefore, we have easily accessed and printed the value of variable name on the console.

But, when we accessed from the main program that calls the function, then we got NameError. This is because the variable defined within a function has a local scope and is only visible inside the function, not outside the function.

Variable Scope and Lifetime in Python


The scope of variable is a region of the program where a variable is visible or accessible. Lifetime of a variable is the duration for which a variable exists in the memory. The existence and accessibility depend on the declaration of a variable in the program.


For example, the lifetime of a variable declared inside a function is as long as the function is alive. When the execution of function body is finished, then the variable defined inside a function will destroy.

Types of Scope of Variables in Python


There are two basic types of scope of variables in Python. They are:

  • Global scope
  • Local scope

Let’s understand each type of variable scope with the help of examples.

Global Scope in Python


When we define a variable inside the main program but outside the function body, then it has a global scope. The variable declared in the main body of the program or file is a global variable.

In the global scope, the global variable will be visible throughout the program or file, and also inside any file which imports that file. We can easily access a variable defined in global scope from all kinds of functions and blocks.

Let’s take some important example programs based on the global scope in Python.


Example 2: 

Let’s write a program in Python in which we will define a global variable and access it from both inside the function and main program body.

# Declaring a global variable in the global scope.
x = 50
# Declare a simple function that prints the value of x.
def showMe():
    print('Value of x from local scope = ',x) # calling variable x inside the function.

# Main program.
showMe() # calling function.
print('Value of x from global scope = ',x)
Output:
      Value of x from local scope =  50
      Value of x from global scope =  50

In this example, variable x is a global variable. We have accessed it from both inside the function and outside the function because it has a global scope.

Local Scope


A variable defined or created inside a function body or a block has a local scope. We can access it only within the declared function or block and not from outside that function or block.

As the execution of function body or block is finished, Python destroys the local variable from the memory. In other words, local variable exists in the memory as long as the function is executing.

Consider the following example code below in which we will define a local variable within in a function and we will access it inside a function and from outside the function.

Example 3:

def my_funct():
    msg = 'Good morning!' # local variable with local scope.
    print(msg) # accessing local variable from inside the function.
my_funct()
print(msg) # accessing local variable from outside the function.
Output:
       Good morning!
       print(msg) # accessing local variable from outside the function.
       NameError: name 'msg' is not defined

As you can see in the output, as we called local variable from outside the function or main program, we got error because Python destroyed the local variable after the execution of function. That is, the local variable does not exist outside the function.


When we define a variable inside the function, it is not related to any way to another variable with the same name used outside the function.

However, a variable defined outside a function will be read inside a function only when the function does not change the value. Let’s an example of it.

Example 4:

# Creating a variable city and set to New York.
city = 'New York' # global scope.
def showMe():
    city = 'Dhanbad' # local scope within a function.
    print('City:',city)
# Function call
showMe()
print('City:',city) # accessing global variable from the global scope.
Output:
      City: Dhanbad
      City: New York

In the above program code, first we have assigned a value ‘New York’ to the city, and then printed the value of city on the console after calling the function.

Next, we have created a function named showMe(). Inside the function showMe(), we have defined a variable with the same name as that of global variable but with a change value.

When we accessed this variable, then Python prints the change value on the console, not the value of global variable because it is not related to any way to another variable with the same name used outside the function.

As the execution of function body is completed, the value of city is destroyed because it is a local variable to that function only.

Parameters defined in Function Definition


We define parameter names in the function definition; it behaves like local variables. But they contain some values that we pass into the function to perform the desired action when we call it. Let’s take an example program based on it.

Example 5:

def showMe(msg): # function header with one formal parameter.
    print(msg) # local scope.

# Main program.
showMe('Hi John, Good Morning!')
print(msg) # being local variable, it does not exist outside the function.
Output:
      Hi John, Good Morning!
      Traceback (most recent call last):
      File "C:\Python Project\Scope.py", line 5, in 
       print(msg) # being local variable, it does not exist outside the function.
       NameError: name 'msg' is not defined

In this tutorial, you have learned about the scope in Python with the help of some important example programs. Hope that you will have understood all the basic points related to variable scope and lifetime with practicing all programs.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love