Categories
Python

Python pass statement [With Easy Examples]

Dear learners, how is everything going? Hope that you’re learning well. In our previous tutorial, we learned about Python break and continue statements to control Python loops. In this tutorial, we are going to learn about Python pass statement.

What is the Python pass statement?

You can consider the pass statement as a “no operation” statement. To understand the pass statement in better detail, let’s look at the sample syntax below.

List <- a list of number
for each number in the list:
	if the number is even,
		then, do nothing
	else 
		print odd number

Now if we convert the above things to python,

#Generate a list of number
numbers = [ 1, 2, 4, 3, 6, 5, 7, 10, 9 ]
#Check for each number that belongs to the list
for number in numbers:
        #check if the number is even
	if number % 2 == 0:
                #if even, then pass ( No operation )
                pass
	else:
                #print the odd numbers
		print (number),

The output will be

>>>
================== RESTART: /home/imtiaz/Desktop/pass1.py ==================
1 3 5 7 9
>>>

Where do we use the pass statement?

Before you begin programming, you generally start out with a structure of functions. These functions tell you what elements your code will have and let you keep track of the tasks you are yet to complete.

Considering the same example, if you are planning to create a program with three functions as shown below. You give the names to the functions and then begin working on one of the functions to start off with.

The other functions are blank and have a simple comment stating that its a TODO for you.

def func1():
        # TODO: implement func1 later
 
def func2():
        # TODO: implement func2 later
        
def func3(a):
        print (a)
 
func3("Hello")
 

If you do the above, you’ll get an error as below:

Python pass statement [With Easy Examples]

So how do you tackle this situation? We use the pass statement here.

def func1():
        pass # TODO: implement func1 later
 
def func2():
        pass # TODO: implement func2 later
        
def func3(a):
        print (a)
 
func3("Hello")

For the above code, you will get output like this:

================== RESTART: /home/imtiaz/Desktop/pass3.py ==================
Hello
>>> 

When you work with a huge python project, at one time, you may need something like the pass statement. That’s why the pass statement is introduced in Python.

Conclusion

That’s all for today! Hope that you learned well about the Python pass statement. Stay tuned for our next tutorial and for any confusion, feel free to use the comment box.

Reference: Official Documentation

Leave a Reply

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