The Total
Now for the most important number on the receipt: how much the whole order costs. For a list of numbers, sum() adds them up. But the cart is a list of Item objects, and Python doesn't know how to add those: sum(cart) ends with TypeError: unsupported operand type(s) for +: 'int' and 'Item'.
What you can add up are the prices of the lines. A list comprehension makes a list of them in one line, and sum() adds up that list. Here's the same idea with the lengths of words:
words = ["bread", "milk", "cheese"]
print([len(word) for word in words])
print(sum([len(word) for word in words]))[5, 4, 6]
15Read it as “len(word) for each word in words”: a list of the results. In the same way, [item.line_total() for item in items] is the list of the prices of the lines, [6, 8, 7, 15] for our cart. So cart_total() needs only one line: a return with sum() of that list.
The new function goes under the cart, above print_receipt(). In print_receipt(), print the total after the loop, indented as much as for. Indented inside the loop, the line would be printed after every item.
Instructions
- 1
Under the cart (above
print_receipt()), write a functioncart_total(items)that returnssum()of a list comprehension: the prices of the lines ofitems, fromline_total(). - 2
At the end of
print_receipt(), after the loop (not inside it), store the result ofcart_total(items)in a variabletotaland print it:Total: $36.