5️⃣

11.5 The Return Statement

The Return Statement

A function can return data to the code that called it. This is useful when you don’t want a function to print to the console, but rather process something internally. For instance, you can have a variable to store the value returned by a function. Python can return any data type, as well as objects or even other functions!
def average(numbers): return sum(numbers) / len(numbers)
The code above returns the average of a list of numbers. It uses the built-in sum() and len() methods to sum all of the numbers in numbers and divide that by the length of the numbers list. Notice that if I call the function by itself, there is no output to the console:
numbers = [1, 2, 3] average(numbers)
This is because returning a value simply gives data back to wherever the function was called. If you want to display the data, you’ll need to use a print statement.
numbers = [1, 2, 3] print(average(numbers))
Output:
2
Now you might be thinking, why would I ever want to use a return statement if it doesn’t display anything? Well, return statements are useful for handling data from a function that may not be displayed, or data that might need to be processed before being displayed. For example:
numbers_1 = [1, 2, 3] numbers_2 = [4, 5, 6] numbers_3 = [7, 8, 9] sum_of_averages = average(numbers_1) + average(numbers_2) + average(numbers_3) print(sum_of_averages)
Output:
15
Notice that we called the average() function multiple times.
average(numbers_1) # would return 2 average(numbers_2) # would return 5 average(numbers_3) # would return 8
Thus, when we added the result of those together (2 + 5 + 8), we got 15. Thanks to the return statement, we were able to process that data, adding all of the averages together and then printing that result.
View code on GitHub.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.