The Same Item Twice

The customer wants two more cartons of milk: add_item(cart, "Milk", 2, 2). Your program puts a second milk line on the receipt. That's not wrong, but a real shop would simply change the quantity on the line that's already there: Milk: 6 x $2 = $12.

So before add_item() appends a new item, it must look for an item with the same name in the list. Here's how to find a dictionary in a list and change it:

books = [
    {"title": "The Hobbit", "pages": 310},
    {"title": "Matilda", "pages": 240},
]
for book in books:
    if book["title"] == "Matilda":
        book["pages"] += 10
print(books)
[{'title': 'The Hobbit', 'pages': 310}, {'title': 'Matilda', 'pages': 250}]

The loop variable book isn't a copy: it's the dictionary from the list itself. So when you change book["pages"], the change stays in books.

Now the function. If the loop finds an item with the same name, it increases its quantity and ends the function with return, because the job is done. If the loop goes through the whole list without finding one, the function continues under the loop, and that's where the new item is appended. So the line with .append() belongs after the loop. Inside the loop under an else, it would add a new item as soon as the loop came to an item with a different name, which is the bread right at the start.

And remember that comparing text is exact: "milk" is not the same as "Milk".

Instructions

At the bottom, under the eggs, add two more cartons of milk: add_item(cart, "Milk", 2, 2). A second milk line appears on the receipt.

Change add_item(): after the check of the quantity, go through items in a loop, and if an item has the same name as name, increase its quantity by quantity and end the function with return. Then the receipt has a single milk line, Milk: 6 x $2 = $12, and the total is $54.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/7