Single or multiple return statements in a function [on hold]
- by Juan Carlos Coto
When writing a function that can have several different return values, particularly when different branches of code return different values, what is the cleanest or sanest way of returning?
Please note the following are really contrived examples meant only to illustrate different styles.
Example 1: Single return
def my_function():
if some_condition:
return_value = 1
elif another_condition:
return_value = 2
else:
return_value = 3
return return_value
Example 2: Multiple returns
def my_function():
if some_condition:
return 1
elif another_condition:
return 2
else:
return 3
The second example seems simpler and is perhaps more readable. The first one, however, might describe the overall logic a bit better (the conditions affect the assignment of the value, not whether it's returned or not).
Is the second way preferable to the first? Why?