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

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:
    foo(element)

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        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"?

This question is related to python function return

The answer is


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.


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...

  1. return None or return can be used to exit out of a function or program, both does the same thing
  2. quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
    import site
    
    def func():
        print("Hi")
        quit()
        print("Bye")
  1. exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
import site
    
    def func():
        print("Hi")
        exit()
        print("Bye")
  1. sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
import sys 
  height = 150
  
if height < 165: # in cm 
      
    # exits the program 
    sys.exit("Height less than 165")     
else: 
    print("You ride the rollercoaster.") 
  1. os._exit(n) function can be used to exit from a process, and need to import os module for that.

I would suggest:

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)