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)? 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)? python python

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)?


You could simply use

return

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.


I would suggest:

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


you can use the return statement without any parameter to exit a function

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

or raise an exception if you want to be informed of the problem

def foo(element):    do something    if check is true:        do more (because check was succesful)    else:        raise Exception("cause of the problem")    do much much more...