Skip to content

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

Let’s assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode:

for element in some_list:

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
        return None
    do much much more...

If I implement this in python, it bothers me, that the function returns a None. Is there a better way for “exiting a function, that has no return value, if a check fails in the body of the function”?



You could simply use


which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.

6 People found this is helpful