In this tutorial, we will discuss the pass keyword and, when and where we can use it. We will see examples of pass keyword and understand how it works.
Table of Content
- What is pass keyword
- How to use a pass keyword
What is pass keyword and what it does in python?
Python 3.X versions have 33 keywords and pass is one of them. Like comments in python pass keyword also do nothing when it executes and that’s what it does, do nothing just pass the interpreter.
It is used as a placeholder for the python statements like if, else, for, elif, while, functions, and class.
Let’s take an example to better understand the pass keyword.
In python, if you use an if, elif, else, functions, class, for loops, while loops you need to define their body or block of code correspond to them, if you don’t the python interpreter will throw an error. So, to overcome this error you can use the pass keyword as a body of the corresponding statement and the statement do nothing and throw no error.
Let’s understand it with an example:
What if we do not use the pass keyword?
number = 10 if number == 9: else: print("hello")
File "importt.py", line 3 else: ^ IndentationError: expected an indented block
Behind the code
In the above example, you can see that we have not declared the body of if statement and when the python interpreter reaches at the if statement it did not find any code for if block, even though its expression was wrong, it did not goanna run in either way but it should have a body. At the moment interpreter finds that the if statement does not have a body correspond to it the interpreter threw an error.
Using the pass
number = 10 if number == 9: pass else: print("hello")
in example 2 we have used pass keyword.
Object & Class
- Python Iterators
- Python Generators
- Python Closures
- Python Decorators
- Python Shallow and Deep Copy
- Python Property
- Python Assert