We will often need to return a value from a function. We can do this with the return
statement in Python. We just need to write this in the function definition:
1 2 3 |
return <value_to_return> |
Tip: the function stops immediately when return
is found and the value is returned.
Here we have an example:
1 2 3 4 |
def get_rectangle_area(length, width): return length * width |
Now we can call the function and assign the result to a variable because the result is returned by the function:
1 2 3 4 5 |
>>> area = get_rectangle_area(4, 5) >>> area 20 |
We can also use return
with a conditional to return a value based on whether a condition is True
or False
.
In this example, the function returns the first even element found in the sequence:
1 2 3 4 5 6 7 8 |
def get_first_even(seq): for elem in seq: if elem % 2 == 0: return elem else: return None |
If we call the function, we can see the expected results:
1 2 3 4 5 |
>>> value1 = get_first_even([2, 3, 4, 5]) >>> value1 2 |
1 2 3 4 5 |
>>> value2 = get_first_even([3, 5, 7, 9]) >>> print(value2) None |
Tip: if a function doesn’t have a return
statement or doesn’t find one during its execution, it returns None
by default.