In this lesson, you will learn how to use the return statement to send data back from a function so your program can store or use that result elsewhere.
Why do we need return?
Up until now, you have mostly used functions to perform actions, like print()ing a result to the console. However, once that function finishes, the data it calculated disappears. If you want to use a result—like a calculated tax total or a processed string—later in your program, you must "hand it back" to the part of the code that called the function.
This is exactly what the return statement does. It stops the function’s execution and passes a value back to the caller.
Seeing it in action
Think of a function like a specialized machine in a factory. If you send in raw materials, you expect the machine to output a finished product. If the machine just destroys the product, it’s not very useful!
Consider this code:
def calculate_area(length, width):
area = length * width
return area # This sends the value back to where the function was called
# We "capture" the returned value in a variable
my_room = calculate_area(10, 12)
# Now we can use that variable for further processing
print(f"The total area is {my_room} square feet.")
When you call calculate_area(10, 12), Python executes the code inside, calculates 120, and the return statement effectively replaces the entire function call with the number 120. That value is then stored in the variable my_room.
Without the return statement, the variable my_room would be empty (or None), and your program wouldn't have the result it needs to move forward. By returning values, you allow your functions to become building blocks that pass data to one another, making your code modular and reusable.
Key Takeaway: Use the return statement to output data from a function so that the result can be captured in a variable or used in subsequent logic.