Night 8: Keep playing
כבר השלמתם את הערב הזה, בפייתון או בפסאודו-קוד. הוא נחשב לשניהם. תוכלו לתרגל שוב אם תרצו.
Tonight: keep playing
- Welcome to week 2! This week your pet plays games.
- You will learn one thing: the
WHILEloop.
Words for tonight
| Word | Meaning |
|---|---|
| while | as long as something is true |
| condition | a question with the answer TRUE or FALSE |
| stop | end; do not go on |
A loop that checks first
- A
FORloop knows how many times to run. - A
WHILEloop does not. It asks a question each time: is the condition still TRUE? - TRUE: run the lines inside again. FALSE: go on after
ENDWHILE.
DECLARE Energy : INTEGER
Energy ← 3
WHILE Energy > 0
OUTPUT "Play! Energy: ", Energy
Energy ← Energy - 1
ENDWHILE
OUTPUT "Time to rest"
Change something inside the loop
- Look at
Energy ← Energy - 1above. It makes the energy smaller each time. - Without this line,
Energy > 0is always TRUE. The loop never stops. - A loop that never stops is called an infinite loop. If it happens, press Stop.
WHILEchecks before the first time. If the condition is FALSE at the start, the loop runs zero times.
Stop when the user says so
- Sometimes you do not know how many times to repeat.
- Your pet thinks of the number 5. The loop goes on until the user types 5.
DECLARE Guess : INTEGER
INPUT Guess
WHILE Guess <> 5
OUTPUT "No, try again"
INPUT Guess
ENDWHILE
OUTPUT "Yes, it was 5!"
<>means is not equal to. Read the next answer inside the loop.
FOR or WHILE?
| You know… | Use |
|---|---|
| how many times: 5 stars, each element of an array | FOR |
only when to stop: until stop, until energy is 0 |
WHILE |
- 9618 also has
REPEAT … UNTIL, which checks after each time. You will meet it on night 26. - Now do the tasks. Your pet is ready to play!
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
Read a number with INPUT N. Use a WHILE loop to output the number, then one less, down to 1. Then output Go! once.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
Your pet wants to play. Read a word with INPUT Word. While the word is not stop, output the word with ! after it, and read the next word. At the end, output Bye!.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
Your pet has Energy ← 10. Each jump uses 3 energy. While Energy is more than 0, output Jump! and the energy, then take away 3. At the end, output Tired. The first line is Jump! 10.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Your pet has Stars ← 1. Every night the stars double. Use a WHILE loop to count the Nights until there are 100 stars or more. Output Nights. The answer is 7.
לחץ על הרץ כדי לראות את התוצא כאן.