Night 11: Teach your pet a trick
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: 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: procedures.
Words for tonight
| Word | Meaning |
|---|---|
| procedure | a named block of code; a trick with a name |
| define | say what something is; teach the trick |
| call | use the procedure; ask for the trick |
Define a procedure
PROCEDURE, then the name and brackets().ENDPROCEDUREends it.- The lines between them are the trick.
PROCEDURE Wave()
OUTPUT "*waves*"
OUTPUT "Hello!"
ENDPROCEDURE
OUTPUT "I know a trick now."
- Press Run. Only the last line runs! You taught the trick, but you did not ask for it.
Call the procedure
- To use the trick, write
CALLand its name:CALL Wave().
PROCEDURE Wave()
OUTPUT "*waves*"
ENDPROCEDURE
CALL Wave()
CALL Wave()
- Each call runs all the lines inside the procedure.
Why use procedures?
| Without a procedure | With a procedure |
|---|---|
| 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() |
Procedures can call procedures
- A big trick can be made from small tricks.
PROCEDURE Wave()
OUTPUT "*waves*"
ENDPROCEDURE
PROCEDURE Jump()
OUTPUT "*jumps*"
ENDPROCEDURE
PROCEDURE Party()
CALL Wave()
CALL Jump()
OUTPUT "Party time!"
ENDPROCEDURE
CALL Party()
- In 9618, a procedure does a job. On night 13 you meet a function, which gives back a value.
- Now teach your pet some tricks in the tasks!
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
Teach your pet its first trick. Write a procedure Wave() that outputs *waves*. Then call it two times with CALL.
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
Write two more tricks: Sit() outputs *sits* et Spin() outputs *spins*. Then call Sit(), Spin() et Sit() again.
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
Write Show(). It calls Wave(), then Sit(), then outputs Ta-da!. Call Show() once.
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
Write Bedtime(). It uses a FOR loop to output Zzz three times. Call it once.
Cliquez sur Exécuter pour voir le résultat ici.