Pass Statement in Python Programming

What is Pass Statement in Python?

Pass Statement in Python: Pass statement in Python is used as a null or blank statement. It is used inside the functions or classes(we will discuss classes in OOPs ) to leave that statement block empty.

This is because, if we leave the statement part of the loop or class empty then it will be considered as syntactically error by the compiler. So to make it syntactically correct we use pass-statement.

Let’s make it more clear, suppose we are declaring a function. But we want to write its code later. But in python, declaring a function without defining its functionality is not considered correct. Below is some example of pass statement in python.

pass statement in python

Example 1:

def fncn():
    #function without body, it will display error

# output
# File "main.py", line 2                                                    
               ^     
# SyntaxError: unexpected EOF while parsing


Example
2:

def fncn():
    pass

# output
# <blank>
# it will not display any error
# because our function is not empty now

Explanation:

  • Hence we can observe that by example 1 & example 2, in example 1 we declared function without writing its functionality or without a statement in its body and it displayed error. But in example 2 we used pass-statement and our error is solved.
  • There is no other thing to learn in pass-statement, so I will going to wrap up this concept with one example so that you can understand where we mainly use pass-statements.

Exercise 1: Write a program to display only those numbers from a list that are not divisible by 5

Example of pass statement in python

#Pass statement examples
x = [1,2,3,4,5,10]
for i in x:
    if(i%5 == 0):
        pass
    else:
        print(i)

# output
# 1
# 2
# 3
# 4

Explanation:

  • Here in this exercises, we initialised a list x with some random numeric values.
  • Next, we used for loop to iterate over each item of list x and in the very next line we are checking whether each element is the modulo of 5.
  • If the condition is True then we are skipping that number using pass statement and in the else block we are printing the number which does not satisfy the condition of the if statement.
  • Hence, the result is obtained.

 

Note: Now many of us may be thinking that why we have not used comment followed by # in the function body instead of pass. The answer is that comment is totally ignored by the compiler but the pass-statement is still considered by the compiler. Hence comment and pass-statement are totally different.