python · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
else runs when all went well, and runs no matter what.
A try can have several except blocks, one for each kind of error you expect, and Python runs the first one that matches. Dividing by zero gives a , and a missing key gives a KeyError.
Add an else block after them for code that should run only when the try worked. Keeping it out of try means its own mistakes are never caught by accident.
A finally block always runs last, error or not. It is the place for clean-up, like saying goodbye or locking a door.
for friends in [4, 0]:
try:
each = 12 // friends
except ZeroDivisionError:
print("Nobody to share with!")
else:
print(f"{each} sweets each")
finally:
print("Sharing done.") The order is always try, then except, then else, then finally.
guess first
Beans are off the menu. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
menu = {"chips": 2.5, "peas": 1.0}
order = "beans"
try:
price = menu[order]
except KeyError:
print(f"No {order} today")
except ValueError:
print("Bad price")
else:
print(f"That is £{price:.2f}")
your turn
Your turn. Finish the door entry system.
Fill in the three missing words: one block for a wrong code, one for a right code, and one that always runs. We will type 1234.
fix it
No marks yet, and it crashes. Can you fix it?
- Read the error: a NameError for
average. Why was it never stored? - The division failed, so
averagewas never made. The last line should only run when thetryworked. - Add a line saying else: above the last print, and indent that print under it.
nailed it
you planned for every outcome. :D
- Use one
exceptfor each kind of error you expect. elseruns only when thetryblock worked.finallyalways runs, so use it for clean-up.
new words in your collection
- finally
- ZeroDivisionError
This lesson isn’t saved. A free account remembers every lesson you finish.