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.

    1. a = 10
    2. b = 0
    3. try:
    4. print(a / b)
    5. except ZeroDivisionError:
    6. pass
    7. 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").

    an example of a required code block

    To address this, I use the pass statement under the except clause.

    This way, the syntax rules of the language are respected.

    the solution to the problem

    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.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python (exceptions)

    1. How to handle exceptions

    Statements

    1. try except
    2. pass
    3. raise
    4. sys.exc_info()