Python pass statement is used as a placeholder when no action is required in the code. In this chapter, you will learn about the Python pass statement, how it works, and where it is used in programs.
The pass statement is a null operation that does nothing when executed. It is used when a statement is required syntactically, but you do not want to write any code at that place.
It is commonly used in loops, functions, classes, or conditional statements where code will be added later. The pass statement ensures that the program runs without errors even when no action is performed.
The syntax of the pass statement in Python is as follows:
Syntax Explanation
The pass statement is used as a placeholder inside a block where a statement is required. In the above example, the function is defined but has no code inside it. The pass statement ensures that the program does not give an error and allows you to add code later.
Let us see a simple example to understand how the pass statement works in Python.
In the following example, we are using the pass statement as a placeholder inside a function.
Explanation:
In this example, we have defined a function greeting() but have not added any code inside it. The pass statement acts as a placeholder, so the function runs without error but does not produce any output.
The Pass statement in Conditional statements - if, else, elif, is used when we want to leave a space or placeholder for any particular condition.
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.
Pass statements in Loops - for, while, are used to symbolize that no action is performed and required during iteration.
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.
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.
Explanation:
The TpointTech 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.
We request you to subscribe our newsletter for upcoming updates.