5.3 Return Values
We learn how functions can return results back to the calling code using the return statement.
While some functions simply perform an action (like `print()`), many times we want a function to calculate something and give us back the result. This is done with the `return` statement.
When Python encounters a `return` statement, it immediately terminates the function's execution and "sends back" the value following `return` to the code that called it. A function can return any data type: a number, a string, a list, a dictionary, or even another function!
If a function does not have an explicit `return` statement, it automatically returns the special value `None`. A function can also return multiple values, which Python automatically "packs" into a tuple.
# Function that returns one value
def calculate_sum(number1, number2):
"""Calculates the sum of two numbers and returns it."""
return number1 + number2
# We store the returned value
my_sum = calculate_sum(10, 7)
print(f"The sum is: {my_sum}")
# Function that returns multiple values
def calculate_stats(number_list):
"""Returns the sum, average, and maximum of a list."""
if not number_list:
return 0, 0.0, None
total = sum(number_list)
average = total / len(number_list)
maximum = max(number_list)
return total, average, maximum
data = [10, 20, 30, 40, 50]
data_sum, data_avg, data_max = calculate_stats(data)
print(f"Sum: {data_sum}, Average: {data_avg}, Maximum: {data_max}")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.