J Atkin
J Atkin

Reputation: 3140

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?

Upvotes: 3

Views: 2069

Answers (3)

miki725
miki725

Reputation: 27861

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!')

Upvotes: 10

Anton
Anton

Reputation: 161

Pass does nothing. When the program gets there, it says "ok skip this!".

Pass can be used to define functions ahead of time. For example,

def function_somebody_is_going_to_write_later():
    pass

def function_I_am_going_to_write_later():
    pass

That way you could write a file with functions that other people might work on later and you can still execute the file for now.

Upvotes: 0

Mijamo
Mijamo

Reputation: 3516

pass does not mean "leave the function", it just means ... nothing. Think of it as a placeholder to say that you do not do anything there (for example if you do not have implemented something yet). https://docs.python.org/3.5/tutorial/controlflow.html#pass-statements

If you want to exit the function, you just return or return None

By the way other useful statements are break to exit the latest loop and continue to exit the current iteration of the loop and directly go to the next one.

Upvotes: 4

Related Questions