Python pass Keyword



The Python pass keyword is a null statement, which can be replaced with future code. It is a case-sensitive keyword. It is used when we wanted to implement the function or conditionals statements in future, which is not implemented yet.

When we define a loop or function if we leave the block empty we will get an IndentationError so, to avoid this error we use pass keyword.

The pass and comments similar in functionality. The only difference is comments are non-executable lines, whereas the pass keyword is executable but results nothing.

Following is the basic syntax of the Python pass keyword −

if True:
    pass

Output

As the above code is empty it result null in the output.

Without pass

If we defined a function or loop, and the block is empty. when we execute the block it will result an IndentationError.

Example

Here, we have defined a while loop with empty block and when we executed it resulted an error −

while True:
    #Empty block

Output

Following is the output of the above code −

File "/home/cg/root/30883/main.py", line 3
    
IndentationError: expected an indented block after 'while' statement on line 1

Using the pass Keyword in Functions

When we define a empty function but would like to reuse it in future we need use pass keyword inside the function else, it will raise an IndentationError. When we call an empty function it will return None.

Example

In the following example, we have defined an empty function Sum() and when we called the Sum() function it returned None

def Sum(a,b):
    pass
	
var1 = 12
var2 = 14
result_1 = Sum(var1, var2)
print("The Result of Empty Function :", result_1)

Output

Following is the output of the above code −

The Result of Empty Function : None

Using pass Keyword within the class

When we defined an empty class, we need to use pass keyword to avoid an IndentationError.

Example

Here, we have created an empty class, Tp(). And created an object for it −

class Tp():
    pass    
Obj1= Tp()
print(Obj1)

Output

Following is the output of the above code −

<__main__.Tp object at 0x0000020193F99A60>
python_keywords.htm
Advertisements