Night 26: Oops-proof
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: oops-proof
- People type the wrong things. A good program does not break.
- You will learn one thing:
tryandexcept.
Words for tonight
| Word | Meaning |
|---|---|
| error | a problem that stops the program |
| try | do something that might go wrong |
| valid | correct and allowed |
The problem
int("five")cannot work. Python stops with an error:
| Code | Result |
|---|---|
int("7") |
7 |
int("five") |
ValueError — the program stops |
10 // 0 |
ZeroDivisionError — the program stops |
Plan A and plan B
- Put the risky code in
try:. Put plan B inexcept.
text = "five"
try:
n = int(text)
print("The number is", n)
except ValueError:
print("Oops, that is not a number")
print("The program goes on!")
- Change
"five"to"5"and press Run again.

Ask again
- Put
tryinside a loop with a flag. Ask until the answer is good.
answers = ["abc", "x", "8"]
ok = False
i = 0
while not ok:
try:
n = int(answers[i])
ok = True
except ValueError:
print(answers[i], "is not a number")
i = i + 1
print("Got", n)
- In the tasks, the answers come from
input(). - Now make your pet's programs oops-proof!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read a number with int(input()) inside try. If it works, print Got and the number. If the user types words, print That is not a number.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Keep asking until the user types a real number. After each bad answer, print That is not a number. At the end, print Thanks! and the number.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now the number must also be from 1 to 10. For a number outside, print Pick 1 to 10 and ask again. For words, print That is not a number.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Share snacks with friends. Read snacks, then friends. Print snacks // friends. If friends is 0, catch the ZeroDivisionError and print No friends to share with.
คลิก Run เพื่อดูผลลัพธ์ที่นี่