Night 11: Teach your pet a trick
Вы уже прошли этот вечер на Python или псевдокоде. Он засчитывается для обоих языков. При желании можете потренироваться ещё раз.
Tonight: teach your pet a trick
- Your pet can learn tricks! You teach a trick once, then use it again and again.
- You will learn one thing: functions.
Words for tonight
| Word | Meaning |
|---|---|
| function | a named block of code; a trick with a name |
| define | say what something is; teach the trick |
| call | use the function; ask for the trick |
Define a function
defmeans define. Then the name, brackets()and a colon:.- The indented lines are the trick.
def wave():
print("*waves*")
print("Hello!")
- Press Run. Nothing happens! You taught the trick, but you did not ask for it.
Call the function
- To use the trick, write its name with brackets:
wave().
def wave():
print("*waves*")
wave()
wave()
- Each call runs all the indented lines of the function.
Why use functions?
| Without a function | With a function |
|---|---|
| copy the same lines again and again | write them once |
| a change means changing every copy | change one place |
| long code that is hard to read | short names like wave() |
Functions can call functions
- A big trick can be made from small tricks.
def wave():
print("*waves*")
def jump():
print("*jumps*")
def party():
wave()
jump()
print("Party time!")
party()
- Define a function before you call it.
- Now teach your pet some tricks in the tasks!
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Teach your pet its first trick. Define a function wave() that prints *waves*. Then call it two times.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Define two more tricks: sit() prints *sits* и spin() prints *spins*. Then call sit(), spin() и sit() again.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Define show(). It calls wave(), then sit(), then prints Ta-da!. Call show() once.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Define bedtime(). It uses a for loop to print Zzz three times. Call it once.
Нажмите Запустить, чтобы увидеть результат здесь.