The Shopping Cart
Welcome to the last lesson of the Python course! In it, you'll put together everything you've learned and build one useful program step by step: the receipt for an order from an online grocery shop. When you finish, your program will print this:
Can't add Eggs: the quantity must be at least 1.
RECEIPT
Bread: 2 x $3 = $6
Milk: 6 x $2 = $12
Cheese: 1 x $7 = $7
Chocolate: 3 x $5 = $15
Coffee: 2 x $7 = $14
Total: $54
Delivery: free
To pay: $54The program works out the price of each line and of the whole order, decides whether the delivery is free, and checks the items that the customer adds to the cart. You'll use variables, f-strings, conditions, lists, loops, functions and dictionaries: everything from the course. Each exercise continues where the previous one ended (the editor starts with its finished code) and adds one piece.
The data. The cart is in the variable cart at the top of the program. It's a list of dictionaries, one for each item. Each dictionary has three keys: "name", "price" (the price of one piece, in whole dollars) and "quantity" (how many pieces the customer wants). Notice the comma after the last dictionary: Python allows it, and it makes adding another item easier. In a real shop, the data would come from the website. The programs here get their data from variables.
The plan. The program is split into functions, each with one job. So far, there's one: print_receipt(items), which prints the receipt for the list of items it gets as an argument. For now, it prints only the heading. At the very bottom, the program calls it with our cart. That's the usual shape of a program: the data at the top, then the functions, and at the end the code that uses them.
Inside the function, work with the parameter items, not with cart. Then the function prints the receipt for whatever list it gets, not just for this one cart.
A reminder of how to go through a list of dictionaries:
books = [
{"title": "The Hobbit", "pages": 310},
{"title": "Matilda", "pages": 240},
]
for book in books:
print(f"{book['title']}: {book['pages']} pages")The Hobbit: 310 pages
Matilda: 240 pagesNotice the quotes: the f-string is in double quotes, so the keys inside it are in single quotes. Double quotes inside double quotes work only in newer versions of Python.
Instructions
In print_receipt(), under the line that prints the heading, write a for loop that goes through items and prints the name of each item.
Complete the line in the loop so that it also shows the quantity and the price of one piece. Use an f-string. The first line of the receipt will be Bread: 2 x $3. The $ is ordinary text in the f-string: write it right before the braces with the price, without a space.
Start programming for free
1/7