×

python · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.