Start learning free

LESSON 161 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 - Cart Sum in Python

Practice

Use a for loop over parallel lists to compute a running total across several items.

You start with:

items = ["Shirt", "Pants", "Shoes", "Hat"]
prices = [25, 40, 60, 15]
quantities = [2, 1, 1, 3]

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result. Just store the text in result; you do not need to print it.

Start with lines = [] and total = 0 before the loop, then append each formatted line and add to total.

Use "\n".join(lines) at the end.

items = ["Shirt", "Pants", "Shoes", "Hat"]
prices = [25, 40, 60, 15]
quantities = [2, 1, 1, 3]

lines = []
total = 0
for i in range(len(items)):
    sub = prices[i] * quantities[i]
    total = total + sub
    lines.append(items[i] + " x" + str(quantities[i]) + ": $" + str(sub))
lines.append("Total: $" + str(total))
result = "\n".join(lines)

STEP 1 OF 8
    Ctrl + Enter to check

    Shopping Cart V4 in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free