Night 13: Your pet answers
Vous avez déjà terminé cette soirée, en Python ou en pseudocode. Elle compte pour les deux. Entraînez-vous à nouveau si vous le souhaitez.
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!
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
Define double(n). It rendements n times 2. Then print double(4). The output is 8.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
Define is_hungry(food). It returns True when food is less than 3, and False otherwise.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Define mood(energy). It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Define bigger(a, b). It returns the bigger of the two numbers. If they are the same, return either one. Do not use max.
Cliquez sur Exécuter pour voir le résultat ici.