Pass Keyword in Python

    In this tutorial, we will discuss what the pass keyword is and when and where we can use it. We will see examples of pass keyword and understand how it works. So let's discuss Pass keyword in Python.

    What is the 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.

    Example Let’s understand it with an example:

    1. What if we do not use the pass keyword?

    number = 10
    if number == 9:
    else:
        print("hello")

    #Output

    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 the interpreter finds that the if statement does not have a body corresponding to it the interpreter threw an error.

    1. Using the pass

    number = 10
    if number == 9:
        pass
    else:
        print("hello") 

    #Output hello in example 2 we have used pass keyword.