Python Return Values
return hands a value out of the function, and the call is that value. cups_left takes started and drank. It returns started - drank. So cups_left(3, 1) is the number 2.
The print sits outside the function. It writes whatever the call is. cups_left has no print of its own.
def cups_left(started, drank):
return started - drank
print(cups_left(3, 1))
The screen shows 2. cups_left did not write that line. print did, because the call is the number 2. The same function with other numbers subtracts those numbers. cups_left(3, 3) is 0, because 3 - 3 is 0.
A line under return is still indented, so it belongs to the function. It does not run. return leaves the function at once, and Python never reaches that line.
def cups_left(started, drank):
return started - drank
print("done")
print(cups_left(3, 1))
The screen shows 2. done is not written. print("done") is indented under def, and return already left the function.
Leave return out, and the call is None. None means no value. greet prints its name and does not return. The word lida on the screen comes from that inner print. The call itself is None.
def greet(name):
print(name)
print(greet("lida"))
The screen shows lida, then None. greet wrote lida. The outer print wrote the value of the call. That value is None, because greet has no return.
Three calls, and what each call is. The greet row is None even though the screen also shows lida. That lida is the inner print, not the value of the call.
📊 What the call is
| Call | Value of the call |
|---|---|
| cups_left(3, 1) | 2 |
| cups_left(3, 3) | 0 |
| greet("lida") with no return | None |
The next page is about where a name can be seen. This page only covers the value a call becomes.
Before you answer
- What does print(cups_left(3, 1)) write?
- What is cups_left(3, 3)?
- print("done") sits under return. Is done written?
- greet only prints. What two lines does print(greet("lida")) write?
The value of the call
return started - drank makes the call that number. print(cups_left(3, 1)) writes 2, and cups_left(3, 3) is 0. A line under return does not run, so done never appears. With no return, print(greet("lida")) writes lida and then None.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top