return
- Python course
- Beginner
- Lesson 72/116
- 4 min
Learn to return values with return.
Returning values with return
A function can compute and return a value; for this, use return:
def add(a, b):
return a + b
result = add(3, 4) # 7When return runs, the function ends and the value goes to the caller. Without return, the function returns None.
Most functions return a value; this value can be passed to another function.
return vs print
print writes a value to the screen but does not return it. return gives the value to the caller:
def show(x):
print(x) # writes to screen, returns None
def give(x):
return x # returns, does not printThese two are often confused. If you will use the result elsewhere, use return; to just see it, use print.
Practice Write an addition function
Define a function called add that takes two parameters a and b and returns a + b. Assign add(3, 4) to result. Then print print(result).
Starter code
# Define the add functionSample solution
def add(a, b):
return a + b
result = add(3, 4)
print(result)Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the return expression
def add(a, b):
____ a + b
def add(a, b):
return a + b
Explanation: return a + b sends the value out.
2 Match return and print
| Term | Meaning |
|---|---|
return |
Returns a value |
print |
Writes to screen |
None |
Default if no return |
def |
Definition keyword |
3 What does this function return? def f(): print("hello")
- "hello"
- None Correct answer
- True
- Raises an error
Explanation: print does not return; the function returns None.