
Hi Ambika! It's natural to get confused by the return statement at the very beginning. So I'll try and help clarify your confusion.
For starters, you can think of a Python function as a machine that takes input (these are the function arguments) and spits out an output (this is the return value).
In other words, the return statement tells the function what "output" to give. You can then use this "function output" (return value) to perform some other operation.
For instance, let's say you need to crate two functions:
One for finding the sum of 3 numbers.
The other for finding the average from the sum.
Let's see how we can solve this problem.
Bad Practice: Without Using return Statement
# Function to calculate sum of 3 numbers
def calculate_sum(n1, n2, n3):
total = n1 + n2 + n3
print(f"Sum = {total}")
# Function to calculate the average of 3 numbers
def calculate_average(n1, n2, n3):
average = (n1 + n2 + n3) / 3
print(f"Average = {average}")
calculate_sum(5, 6, 7)
calculate_average(5, 6, 7)Here, you can't use the sum calculated by the calculate_sum() function inside the calculate_average() function. As a result, we need to calculate the sum all over again inside calculate_average().
There are ways to work around this issue, but they're awkward and unsafe. The most natural and desirable solution is to use the return statement.
Good Practice: Using return Statement
# Function to calculate sum of 3 numbers
def calculate_sum(n1, n2, n3):
return n1 + n2 + n3
# Function to calculate the average of 3 numbers
def calculate_average(total):
return total / 3
# Store the return value in my_sum variable
my_sum = calculate_sum(5, 6, 7)
# Print the sum
print(f"Sum = {my_sum}")
# Pass my_sum as argument to calculate_average()
# And store the return value in my_average
my_average = calculate_average(my_sum)
# Print the average
print(f"Average = {my_average}")As you can see, using the return statement allows you to use your first calculation in other parts of the program, such as sending it as an argument to the calculate_average() function.
And this is just a small program!
Imagine how handy return values will be when you have to write a large program that has multiple functions, and you need to use the results of those functions in other parts of the program.
This is the true power of the return statement. Hope everything's clear now!
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer