Return Values¶
All of the function we have written so far have printed some sort of message. However, we will not always desire this sort of behavior. Most of the pre-defined functions we have seen in this course print nothing at all, but instead provide some sort of output that can be printed, or stored into a variable.
For example, the sum()
function takes a list as an input, and provides the sum of the values in the list as the output. When a function provides an output, that output is called a return value.
The syntax for defining a function with a return value is as follows:
def my_function(parameter1, parameter 2, ...):
Code to be executed.
return value_to_be_returned
As a simple example, the cell below defines a function called half()
that accepts a single input, and returns the input divided by 2.
def half(x):
return x/2
y = half(36)
print(y)
18.0
half(9) + half(14)
11.5
print(half(100))
print(half(35))
print(half(3.14159))
50.0
17.5
1.570795
We can nest function calls inside of each other. In this way, the return value for one function call becomes the argument for another.
one_eighth = half(half(half(20)))
print(one_eighth)
2.5
Multiple Return Statements¶
It is possible for a function to have multiple return statements. As soon as a return statement is hit, however, the function returns that value and then exits. As an illustration of this idea, compare the following two functions, both of which return the absolute value of a number.
def abs_val_1(x):
if (x < 0):
absVal = -x
else:
absVal = x
return absVal
print(abs_val_1(9))
print(abs_val_1(-3.8))
9
3.8
def abs_val_2(x):
if(x < 0):
return -x
return x
print(abs_val_2(9))
print(abs_val_2(-3.8))
9
3.8