Dear learners, how is everything going? Hope that you’re learning well. In our previous tutorial, we learned about Python break and continue statement to control python loops. You can find that tutorial here. In this tutorial, we are going to learn about Python pass statement.
Python pass statement
You can consider python pass statement as no operation statement. The difference between Python comments and pass statement is; comments are being eliminated while interpreting the program but pass statement does not. It consumes execution cycle like a valid statement. For example, for printing only the odd numbers from a list, our program flow will be:
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 >>>
Suppose you need to implement many function one by one. But you have to check every function after implementing the function. Now if you leave the things like this:
def func1(): # TODO: implement func1 later def func2(): # TODO: implement func2 later def func3(a): print (a) func3("Hello")
Then, you will get IndentationError for this.
So, what you need to do is, add pass statement to each no-implemented function like this.
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 >>>
Why should we use Python pass Statement
Now, a question may come to your mind, why should we use Python pass statement? Actually it seems that, in our previous example, if we just comment-out the unimplemented functions, like below, we will still get our desired output.
#def func1(): # TODO: implement func1 later #def func2(): # TODO: implement func2 later def func3(a): print (a) func3("Hello")
But if you work with a huge python project, at one time, you may need something like pass statement. That’s why pass statement is introduced in Python.
That’s all for today. Hope that, you learned well about Python pass statement. Stay tuned for our next tutorial and for any confusion, feel free to use the comment box.
Reference: Official Documentation