Night 26: Oops-proof
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: oops-proof
- People type the wrong things. A good program does not break.
- You will learn one thing: input checks, and the
REPEAT … UNTILloop.
Words for tonight
| Word | Meaning |
|---|---|
| error | a problem that stops the program |
| check | test something before you use it |
| valid | correct and allowed |
Read text, then check it
- If you
INPUTinto an INTEGER and the user typesfive, the program breaks. - So read into a STRING. Then check it with
IS_NUMand convert it withSTR_TO_NUM.
DECLARE Answer : STRING
Answer ← "five"
IF IS_NUM(Answer) THEN
OUTPUT "The number is ", STR_TO_NUM(Answer)
ELSE
OUTPUT "Oops, that is not a number"
ENDIF
OUTPUT "The program goes on!"
- Change
"five"to"5"and press Run again.

REPEAT … UNTIL
REPEATruns the lines first, then checks the condition atUNTIL.- It stops when the condition is TRUE. So it always runs at least once.
DECLARE Answer : STRING
REPEAT
OUTPUT "Type a number:"
INPUT Answer
UNTIL IS_NUM(Answer)
OUTPUT "Thanks! ", Answer
| Loop | Checks | Runs at least once? |
|---|---|---|
WHILE … ENDWHILE |
before | no |
REPEAT … UNTIL |
after | yes |
Two kinds of check
| Check | Question | Example |
|---|---|---|
| type check | is it a number at all? | IS_NUM(Answer) |
| range check | is the number allowed? | Number >= 1 AND Number <= 10 |
- Now make your pet's programs oops-proof!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read the answer into a STRING Answer. If IS_NUM(Answer), output Got and the number from STR_TO_NUM. If not, output That is not a number.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Keep asking until the user types a number. Use REPEAT … UNTIL. After each bad answer, output That is not a number. At the end, output Thanks! and the answer.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now the number must also be from 1 to 10. For a number outside, output Pick 1 to 10 and ask again. For words, output That is not a number. At the end, output Thanks! and the number.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Share snacks with friends. Read Snacks, then Friends. Output Snacks DIV Friends. If Friends is 0, output No friends to share with instead.
คลิก Run เพื่อดูผลลัพธ์ที่นี่