Night 13: Your pet answers
You already finished this night, in Python or pseudocode. It counts for both. Practise again if you like.
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!
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Define double(n). It returns n times 2. Then print double(4). The output is 8.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Define is_hungry(food). It returns True when food is less than 3, and False otherwise.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Define mood(energy). It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Define bigger(a, b). It returns the bigger of the two numbers. If they are the same, return either one. Do not use max.
Click Run to see the output here.