Night 13: Your pet answers
Вы уже прошли этот вечер на Python или псевдокоде. Он засчитывается для обоих языков. При желании можете потренироваться ещё раз.
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!
Сложность 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.
Нажмите Запустить, чтобы увидеть результат здесь.