Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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]
15

Read 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. 1

    Under the cart (above print_receipt()), write a function cart_total(items) that returns sum() of a list comprehension: the prices of the lines of items, from line_total().

  2. 2

    At the end of print_receipt(), after the loop (not inside it), store the result of cart_total(items) in a variable total and print it: Total: $36.

Back

3/9

  1. 1. The Shopping Cart
  2. 2. The Price of a Line
  3. 3. The Total
  4. 4. Free Delivery
  5. 5. Adding Items
  6. 6. The Same Item Twice
  7. 7. Reading the Order
  8. 8. The Most Expensive First
  9. 9. Congratulations!
Next

Try it yourself

Do this exercise right here in your browser. No account needed.