Python In 30 Days - Day 5
Day 5 was all about handling errors in your code.
The Challenge:
You're hardening your restaurant system against bad input.
Write a program that:
1. Takes your existing menu dictionary and get_total function from Day 2
2. Writes a function safe_add_item(order, item_name, menu) that uses try/except to handle:
- Someone passing a non-string as item_name (catch the right exception when you try to use it as a dictionary key)
- An item that doesn't exist in the menu (there's a specific exception for this — no if/else allowed this time, catch it instead)
3. Writes a function safe_get_total(order, menu) that handles:
- An empty order list — return 0 and print a warning rather than crashing
- Any item in the order that somehow isn't in the menu (catch the right exception, skip that item, and print a warning)
4. Tests your error handling by deliberately passing bad input:
- A non-string item name
- A non-existent item name
- Calling safe_get_total on an empty order
5. Also runs a successful order through both functions to prove they still work normally
Things to figure out: which specific exceptions get raised by a bad dictionary key lookup and by passing the wrong type. Try triggering them intentionally in a scratch file first if it helps — reading the error message Python gives you is the fastest way to learn which exception to catch.
My Code:
menu = {
'Burger': 15,
'Fries': 5,
'Milkshake': 9,
'Salad': 6,
'Brownie': 3
}
order = []
total = 0
# 1 & 2
def safe_add_item(order, item_name, menu):
try:
price = menu[item_name]
except TypeError:
print(f"Sorry, {item_name} is not a string.\n")
except KeyError:
print(f"Sorry, {item_name} is not on the menu!\n")
else:
order.append(item_name)
print(f"Added {item_name} to order.")
# 3
def safe_get_total(order, menu):
if not order:
print("Warning: Your order is empty.\n")
return 0
total = 0
for i in order:
try:
total += menu[i]
except KeyError:
print(f"Warning: {i} is not on the menu. Skipping item.")
return total
# 4
bill_err = safe_get_total(order, menu)
item = ["hello", "food"]
safe_add_item(order, item , menu)
type_err = safe_get_total(order, menu)
# 5
safe_add_item(order, 'Burger', menu)
safe_add_item(order, 'Pizza', menu)
safe_add_item(order, 'Fries', menu)
safe_add_item(order, 'Milkshake', menu)
bill = safe_get_total(order, menu)
print("\nYour order:\n")
print(*order, sep="\n")
print(f"\nTotal: ${bill}")
Running the Code:
Warning: Your order is empty.
Sorry, ['hello', 'food'] is not a string.
Warning: Your order is empty.
Added Burger to order.
Sorry, Pizza is not on the menu!
Added Fries to order.
Added Milkshake to order.
Your order:
Burger
Fries
Milkshake
Total: $29
Apparently the next challenge begins working through Object Oriented Programming, so I'm excited to see what that brings.