Night 13: Your pet answers
你已使用 Python 或伪代码完成过这个夜间练习,两种语言均计入完成记录。你可以再次练习。
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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 |
English
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.

English
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.
English
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!")
English
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!
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Define double(n). It 返回值 n times 2. Then print double(4). The output is 8.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Define is_hungry(food). It returns True when food is less than 3, and False otherwise.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Define mood(energy). It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Define bigger(a, b). It returns the bigger of the two numbers. If they are the same, return either one. Do not use max.
点击“运行”查看此处输出。