Night 13: Your pet answers
כבר השלמתם את הערב הזה, בפייתון או בפסאודו-קוד. הוא נחשב לשניהם. תוכלו לתרגל שוב אם תרצו.
Tonight: your pet answers
- Until now, your pet's tricks did something: they output text.
- Tonight your pet answers. A function gives a value back.
- You will learn one thing:
FUNCTIONwithRETURN.
Words for tonight
| Word | Meaning |
|---|---|
| function | a named block of code that gives a value back |
| return | give a value back to the place where it is used |
| result | the value a function gives back |
Give a value back
- The first line says the type that comes back:
RETURNS INTEGER. RETURNsends the value back. The call becomes that value.
FUNCTION Double(N : INTEGER) RETURNS INTEGER
RETURN N * 2
ENDFUNCTION
DECLARE Answer : INTEGER
Answer ← Double(4)
OUTPUT Answer
OUTPUT Double(10) + 1
Double(4)becomes8.Double(10) + 1becomes20 + 1.

Procedure or function?
PROCEDURE |
FUNCTION |
|---|---|
| does a job | gives a value back |
used with CALL Wave() |
used in an expression: OUTPUT Double(4) |
no RETURNS |
RETURNS and a type |
- Never write
CALL Double(4), and never use a procedure inside anOUTPUT.
Answer a yes/no question
Food < 3is alreadyTRUEorFALSE. A function can return it.
FUNCTION IsHungry(Food : INTEGER) RETURNS BOOLEAN
RETURN Food < 3
ENDFUNCTION
IF IsHungry(1) THEN
OUTPUT "Feed me!"
ENDIF
RETURN ends the function
- When
RETURNruns, the function stops at once.
FUNCTION Mood(Energy : INTEGER) RETURNS STRING
IF Energy > 7 THEN
RETURN "happy"
ENDIF
RETURN "sleepy"
ENDFUNCTION
OUTPUT Mood(9)
OUTPUT Mood(2)
- Now let your pet answer in the tasks!
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
Write a function Double(N : INTEGER) RETURNS INTEGER. It החזרים N times 2. Then output Double(4). The output is 8.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
Write IsHungry(Food : INTEGER) RETURNS BOOLEAN. It returns TRUE when Food is less than 3, and FALSE otherwise.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Write Mood(Energy : INTEGER) RETURNS STRING. It returns "happy" when energy is more than 7, "ok" when it is more than 3, and "sleepy" otherwise.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Write Bigger(A : INTEGER, B : INTEGER) RETURNS INTEGER. It returns the bigger of the two numbers. If they are the same, return either one.
לחץ על הרץ כדי לראות את התוצא כאן.