pythonpython-3.x

Why does python keep evaluating code after `pass`?


I found an interesting piece of code in python:

def x(cond):
    if cond:
        pass
        print('Still running!')

x(True)

I would expect this not to print anything, but it prints Still running!. What is happening here?


Solution

  • As per Python docs:

    pass is a null operation — when it is executed, nothing happens.

    Source - https://docs.python.org/3/reference/simple_stmts.html#pass

    As such, pass does not do anything and all statements after pass will still be executed.

    Another way of thinking about this is that pass is equivalent to any dummy statement:

    def x(cond):
        if cond:
            "dummy statement"
            print('Still running!')