Project: Shopping cart
Real programs mix collections: a dict for the price lookup and a list for what's in the cart.
See it run
prices = {"tea": 2, "jam": 3}
bag = ["jam", "tea"]
first = bag[0]
cost = prices[first]
print(first, cost)The two collections work as a team: the list gives you names, the dict turns each name into a price.
Practice project: shopping cart
Exercise 1
Use cart and prices in the editor below. Make total the price of everything in cart (each name looked up in prices) using a loop or sum. Then print it as Total: $4.45.
Exercise 2
Use cart and prices in the editor below: this cart is a dict of name to quantity. For each item print a receipt line like apple x3 = $1.50 (money with 2 decimals), keep a running total, and finish with Total: $3.90.
Exercise 3
Use cart and prices in the editor below. Some cart items aren't in prices (out of stock).
- Skip unknown items and collect their names in a list
missing. total= the cost of the known items.- If
totalis over 4, take 10% off to getfinal; otherwisefinalequalstotal. - Print
Missing: cheese(names joined by", ") and thenTotal: $4.23.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.