
Code
Catch the Right One
One try can have several except blocks. Python checks them
top to bottom and runs the first one that matches.
prices = {"oil": 3, "wick": 1}
try:
qty = int(input("How many? "))
cost = prices["glass"] * qty
except ValueError:
print("Please type a whole number.")
except KeyError as err:
print("We don't sell", err)
except KeyError as err:stores the exception object inerr, so you can print or inspect its message.- You can catch several types with one block:
except (ValueError, KeyError):. - Anything you don't list is not caught, and that's a good thing! Unexpected errors should stay loud so you notice bugs.
Assignment
A shelf is a list of items. Players pick a slot by typing a number.
- Complete
read_slot(shelf, choice): convertchoicewithint()and return the item at that index ofshelf. - If
choiceisn't a whole number (ValueError), return"Not a number". - If there's no item at that index (
IndexError), return"Empty slot". - Don't catch any other exception types.
A shelf is a list of items. Players pick a slot by typing a number.
- Complete
read_slot(shelf, choice): convertchoicewithint()and return the item at that index ofshelf. - If
choiceisn't a whole number (ValueError), return"Not a number". - If there's no item at that index (
IndexError), return"Empty slot". - Don't catch any other exception types.
main.py Python sleeping
Press Run to try your code, then Check to test it.