The Same Item Twice
The customer wants two more cartons of milk. They typed the name on the website themselves, with a space in front and a small m: " milk". Your program puts a second milk line on the receipt for it, which even starts with that space. 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 an object in a list and change it:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
books = [Book("The Hobbit", 310), Book("Matilda", 240)]
for book in books:
if book.title == "Matilda":
book.pages += 10
print(books[1].pages)250The loop variable book isn't a copy: it's the object from the list itself. So when you change book.pages, the change stays in books.
But comparing text is exact: " milk" == "Milk" is False. Before you compare two names, clean both of them up with the methods from the lesson Working with Text: .strip() removes the spaces around a text, and .lower() makes all its letters lowercase. Then both names give the same text:
print(" milk".strip().lower())
print("Milk".strip().lower())milk
milkNow the function. If the loop finds an item with the same name, it increases its quantity and ends the function with return, with no value after it, 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.
Instructions
- 1
At the bottom, under the
tryblock with the eggs, add the milk as the customer typed it:add_item(cart, " milk", 2, 2). A second milk line appears on the receipt. - 2
Change
add_item(): after the check of the quantity, go throughitemsin a loop. If an item's name is the same asnameonce you've used.strip().lower()on both, increase the item's quantity byquantityand end the function withreturn. Then the receipt has a single milk line,Milk: 6 x $2 = $12, and the total is$54.