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?
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?
As per Python docs:
passis a null operation — when it is executed, nothing happens.
Source - https://docs.python.org/3.5/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!')
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.
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.