Night 13: Your pet answers
لقد أنهيت هذه الليلة بالفعل باستخدام Python أو الشيفرة الكاذبة. وهي تُحتسب لكلتيهما. تدرّب مرة أخرى إن شئت.
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.
اضغط تشغيل لرؤية المخرجات هنا.