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.
点击“运行”查看此处输出。
难度 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.
点击“运行”查看此处输出。
难度 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.
点击“运行”查看此处输出。
难度 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.
点击“运行”查看此处输出。