Return Values
Return Values
Sometimes a function should do more than print something.
Sometimes we want a function to give a result back to us.
Python uses the return keyword for this.
What Is Return?
return sends a value out of a function.
That value can be stored in a variable, printed, or used later.
Why Return Is Useful
With return, a function can:
- Calculate an answer
- Send data back
- Be reused in bigger programs
- Work with other code
Print vs Return
These are not the same.
Using Print
def add():
print(2 + 3)
add()
Output
5
This shows the answer on the screen.
Using Return
def add():
return 2 + 3
result = add()
print(result)
Output
5
This gives the answer back so we can store it.
Another Example
def greet(name):
return "Hello " + name
message = greet("Sara")
print(message)
Output
Hello Sara
Return Stops the Function
When Python reaches return, the function ends.
def test():
return "Done"
print("This will not run")
print(test())
Output
Done
Using Return in Math
def multiply(a, b):
return a * b
answer = multiply(4, 5)
print(answer)
Output
20
Code Along
def square(number):
return number * number
print(square(6))
Output
36
Mini Challenge
Build an add function.
Steps:
- Create a function called
add - Give it two parameters
- Return the total
- Call the function with
3and7 - Print the result
Expected output:
10
Real World Use Case
Programs use return to calculate totals, check results, send data, and build reusable features.
Quiz
- What does
returndo? - Can a returned value be stored in a variable?
- Does the function continue after
return? - What is the difference between
printandreturn?
Assignment
Create a function called subtract that returns the answer of two numbers. Print the result.
Summary
You learned that return sends a value out of a function so it can be used, stored, or printed later.