Students catch errors with try and except so typed mistakes get a reply instead of a crash, compare it with checking first (isdigit), and catch two kinds of error in one program.
Load these into Waypoints Prepare: choose Load URL and paste the copied address, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.
Predict and Run 10 min · Investigate 15 min · Modify 10 min · Make 10 min
Read the unit primer first. try: runs its lines; if one causes the named error, Python jumps to except ThatError: and then carries on after it. Only the named error is caught: the bug task catches ValueError when the error is a KeyError, so the program still stops. int() accepts " 4 " and "-2" but not "3.5" or "three", so a caught error does not check whether a number is sensible (the first Investigate question). Avoid a bare except: that catches everything: it hides real mistakes.
Catching the error that actually happens. Ask them to read the error's name in the message and match it to the except, rather than catching everything.
| What you will see | A question to ask | The fix |
|---|---|---|
| The program still stops with an error. | Which error does the message name, and which does your except catch? | Catch the error the message names (KeyError, not ValueError). |
| The loop never ends, even with a good answer. | Where is break, and does it run when the answer is good? | Put break inside try, after the line that might fail. |
| NameError on a variable after the loop. | Was the variable given a value inside try before the loop ended? | Only leave the loop (break) once the value has been set. |
One possible solution for each task. Other correct programs are fine.
prices = {"pie": 5, "drink": 3, "fruit": 2}
while True:
item = input("What would you like? ").strip().lower()
try:
price = prices[item]
break
except KeyError:
print("We have: " + ", ".join(prices))
while True:
text = input("How many? ")
try:
count = int(text)
if count >= 1 and count <= 10:
break
print("Choose 1 to 10.")
except ValueError:
print("Please type a whole number.")
print("That will be $" + str(price * count) + ".")
prices = {"pie": 5, "drink": 3, "fruit": 2}
price = 0
while True:
item = input("What would you like? ").strip().lower()
if item == "quit":
break
try:
price = prices[item]
break
except KeyError:
print("We have: " + ", ".join(prices))
if item != "quit":
while True:
text = input("How many? ")
try:
count = int(text)
break
except ValueError:
print("Please type a whole number.")
print("That will be $" + str(price * count) + ".")
else:
print("Goodbye!")
while True:
try:
a = int(input("First number: "))
b = int(input("Divide it by: "))
print("Answer: " + str(a / b))
break
except ValueError:
print("Please type whole numbers.")
except ZeroDivisionError:
print("You can't divide by zero. Try again.")
Stretch: Make a function ask_number(question) that keeps asking until it gets a whole number, and use it twice.
Support: Give students the try and the first except of the calculator, and ask them to add the second except.
try: n = int("3.5") except ValueError: n = 0. What is n?
0: int("3.5") causes a ValueError, so the except line runs.
Next lesson is the text adventure. Later, saving and loading a game uses the same idea for a missing file (FileNotFoundError).