In Python, the pass Statement acts as a null operator or placeholder. It is applied when a statement is required syntactically, which means that the statement will be visible in the code but will be ignored; hence, it returns nothing.
Syntax of the Pass Statement
The following below is the syntax of the pass statement in Python:
Syntax:
def func_name():
pass
Simple Python Pass Statement Example
Let us see a simple example to understand how Python’s pass statement works:
Example
# a function to send greetings
def greeting():
# using pass statement
pass # this acts as a placeholder
# calling the function
greeting()
Explanation:
Here, we have defined a function greeting() and used the pass statement to represent the placeholder.
Since this function is empty and returns nothing due to the pass statement, there will be no output when we call this function.
Using Pass Statement in Conditional Statements
The Pass statement in Conditional statements – if, else, elif, is used when we want to leave a space or placeholder for any particular condition.
Example
n=5
if n>5:
pass # this works as a placeholder
else:
print("The defined number n is 5 or less than 5")
Output:
The defined number n is 5 or less than 5
Explanation:
In this example, we used the pass statement in the if-block of the if-else statement. Here, the pass statement is a placeholder indicating that a piece of code can be added in the if-block in the future.
Using Pass Statement in Loops
Pass statements in Loops – for, while, are used to symbolize that no action is performed and required during iteration.
Example
for i in range(10):
if i == 5:
pass #It will give nothing when i=5
else:
print(i)
Output:
0
1
2
3
4
6
7
8
9
Explanation:
When the Pass Statement is used in the ‘if’ condition, it will print every number in the range of 0 to 10 except 5.
Using Pass Statement in Classes:
A pass statement in a Class is used to define an empty class and also as a placeholder for methods that can be used later.
Example
class Learn Python:
pass
class Employees:
def __init__(self,first_name,last_name):
self.ft_name=ft_name #ft_name means first name
self.lt_name=lt_name #lt_name means last name
def ft_name(ft_name):
pass #placeholder for first name
def l_name(l_name):
pass #placeholder for last name
Explanation:
The Learn Python class has no methods or attributes; here, the pass statement is used to describe an empty class.
In the Employees class, the first and last name methods are defined, but they produce nothing, as indicated by the pass keyword.
Conclusion
A pass statement is a prominent way to be used as a placeholder, which does not give any output. It can be used in conditional statements, loops, functions, and classes, which provides coders with a way to define the structure of the code without executing any functionality temporarily.
Leave a Reply