- Explain the difference between a function that prints a value and a function that returns a value.
- Use the
returnkeyword to send a value back from a function. - Capture a function's return value in a variable.
Functions That Give Back an Answer
So far, our functions have only performed actions (like printing to the screen). But what if we need a function to do a calculation and give us back the result so we can use it later in our program? For this, we use the return keyword.
This is a vital concept to understand:
print()is for the human user. It displays a value on the screen for a person to read.returnis for the computer program. It sends a value back to the code that called the function, so the program can store it or use it in another calculation.
The Syntax
The return keyword is usually the last line inside a function. As soon as a function hits a return line, it immediately stops and sends the specified value back.
# This function takes two numbers and RETURNS their sum.
def add_numbers(num1, num2):
result = num1 + num2
return result
# Now, we call the function and CAPTURE its return value in a new variable.
sum_of_numbers = add_numbers(5, 3)
# Now we can use that captured value for other things.
print(f"The result of the function is: {sum_of_numbers}")
print(f"I can use that result in another calculation: {sum_of_numbers * 2}")
Live Example: The Calculator Function
The Trinket below shows the crucial difference between a function that prints and a function that returns. Pay close attention to the comments and the "Your Turn" instructions to see why return is so much more powerful for building complex programs.
Functions that take parameters and return values are the fundamental building blocks of almost all software. You can create a library of these "helper" functions to solve small problems, and then combine them to build large, complex applications. This is the key to our "Simple Calculator" project.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.