Returning a Value
return sends a value back to the code that called the function. It also ends the function.
def double(number):
return number * 2
result = double(21)
print(result)
print(double(10) + 5)
Output:
42
25
double(21) gives back 42, which is stored in result and then printed. In the last line, double(10) gives back 20, and Python adds 5 to get 25.
You can use a returned value like any other value. You can store it in a variable, print it, compare it, or use it in a calculation.
A function with no return gives back None. None is Python's value for "nothing". This is easy to miss when a function prints a value instead of returning it:
def show_double(number):
print(number * 2)
result = show_double(21)
print(result)
Output:
42
None
show_double printed 42 itself, but it did not give anything back. So result is None. Printing shows a value to the person running the program. Returning gives a value to the code that called the function, so that code can keep using it. Keeping these two jobs separate makes a function easier to reuse.
If a function has several branches, each branch that should give an answer must reach a return with the right value.
In the exercise, make both functions return their results.