pass statement in Python explanation with example

pass statement in Python explanation with example:

pass statement in Python is a null statement. pass is not ignored by the interpreter. We can use this statement in place of a code, i.e. at places where without code the program will not run but we don’t have anything to put.

One example of pass is to put it in an empty function. Suppose we create one function and left the body to be implemented later on. We can just put one pass statement in the body of that function.

Similarly, we can put pass in other places like a class, loop, conditional statement etc.

What are the differences between pass and comment:

comment and pass, both are different. We can write one comment to fill a line but the python interpreter treates it differently. It is not a placeholder like pass. It is ignored by interpreter completly. Comments are used as guide in code. If interpreter treats comments similar to code, the program execution time will increase.

For the below program:

def myFutureFuntion():
    # implementation pending

It will throw one error :

SyntaxError: unexpected EOF while parsing

But, if we replace the comment with pass:

def myFutureFuntion():
    pass

It will run.

Examples of pass:

Let me quickly show you how pass works with different examples:

pass with a function:

We can use pass with a function as shown above:

def myFutureFuntion():
    pass

pass with a class:

pass can also be used with a class:

class myFutureClass:
    pass

pass with if-else:

Similarly, we can use it with if or else block:

no = 20

if no%2 == 0:
    pass
else:
    print("Odd")

pass with for loop:

pass can also be used with a loop:

limit = 20

for i in range(limit):
    pass

There are many use cases of pass and it is a better way to use as a null statement other than adding any logs.

You might also like: