Pass Statement in Python
The pass statement does absolutely nothing. It's a convenient placeholder in Python that you can use in your code where a statement is syntactically required.
Syntax
pass
The pass statement produces no output and performs no action.
What is it used for?
It is particularly useful in Python's exception handling.
To illustrate its utility, let's look at a practical example.
A Practical Example
In this example, I intentionally include a division by zero.
This operation is impossible and will generate an error in any programming language.
- a = 10
- b = 0
- try:
- print(a / b)
- except ZeroDivisionError:
- pass
- print("end")
For some reason, I want the program to continue running even if an error occurs.
In line 5, I catch the division by zero error (ZeroDivisionError) using a try except block.
However, the except clause requires an indented block of statements. You must write something; otherwise, the Python interpreter will raise another error ("expected an indented block").
To address this, I use the pass statement under the except clause.
This way, the syntax rules of the language are respected.
Now I run the program with F5 (Run).
The program's output is as follows:
end
Everything runs and works correctly.
The script shows no errors, handles the exception without doing anything, and completes execution to the last line of code.
And that's it.