Night 13: Your pet answers
Bạn đã hoàn thành đêm này bằng Python hoặc mã giả. Kết quả được tính cho cả hai. Bạn có thể luyện tập lại nếu muốn.
Tonight: your pet answers
- Until now, your pet's tricks did something: they printed.
- Tonight your pet answers. A function can give a value back.
- You will learn one thing:
return.
Words for tonight
| Word | Meaning |
|---|---|
| return | give a value back to the place of the call |
| result | the value a function gives back |
| True / False | the two answers to a yes/no question |
Give a value back
returnsends a value back. The call becomes that value.
def double(n):
return n * 2
answer = double(4)
print(answer)
print(double(10) + 1)
double(4)becomes8.double(10) + 1becomes20 + 1.

print or return?
print |
return |
|---|---|
| shows a value on the screen | gives a value back to the code |
| the program cannot use it again | you can save it, add to it, test it |
- Most functions in real programs return. The main program decides what to print.
Answer a yes/no question
food < 3is alreadyTrueorFalse. A function can return it.
def is_hungry(food):
return food < 3
if is_hungry(1):
print("Feed me!")
return ends the function
- When
returnruns, the function stops at once.
def mood(energy):
if energy > 7:
return "happy"
return "sleepy"
print(mood(9))
print(mood(2))
- Now let your pet answer in the tasks!
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Define double(n). It returns n times 2. Then print double(4). The output is 8.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Define is_hungry(food). It returns True when food is less than 3, and False otherwise.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Define mood(energy). It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Define bigger(a, b). It returns the bigger of the two numbers. If they are the same, return either one. Do not use max.
Nhấn Chạy để xem kết quả ở đây.