Start learning free

LESSON 189 OF 673 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Python: Summing Items with a for Loop

Practice Read the full explanation

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

    PYTHON · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Python, explained

    Problem overview

    Version 4 of the cart handles several items at once. The data comes as three parallel lists: items holds the names, prices the unit prices and quantities how many of each were bought. The item at position i in one list matches position i in the others. The program builds one receipt row per item, in the form Name xQ: $subtotal, then a final Total row, and stores everything in the string result.

    For the starting lists the receipt is:

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

    Approach: one pass with a running total

    Each item needs the same work: multiply its price by its quantity, add that to a running total, and write a row. That is a loop. Because the data is split over three lists, the loop walks the positions 0 to len(items) - 1 and reads all three lists at the same position.

    The rows go into a list called lines as they are produced. A list is easier to build up than one long string, and a single join at the end turns it into text. The total row can only be written after the loop, because the total isn't known until every item has been added.

    Step by step

    1. Create lines. An empty list that will hold the rows.
    2. Create total at 0. A running total always starts at zero, before any item is counted.
    3. Loop over positions. for i in range(len(items)) makes i take the values 0, 1, 2, 3 for this data.
    4. Compute sub. It is prices[i] * quantities[i]: this item's price times its quantity.
    5. Add sub to total. After the last pass, total holds the sum of every subtotal.
    6. Append the item's row. The row is the name, a space, an x, the quantity, a colon, a space, a dollar sign and the subtotal. The two numbers go through str().
    7. Append the total row after the loop. This line is not indented, so it runs once.
    8. Join the rows. "\n".join(lines) puts a newline between each two rows and none after the last.

    The solution in Python

    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)
    

    Details worth knowing:

    • range(len(items)). len(items) is 4, and range(4) produces 0, 1, 2 and 3, so i is always a valid position. The end of a range is excluded.
    • Indentation marks the loop body. The first four statements are indented under for, so they run on every pass. The lines.append("Total: $" + str(total)) line is back at the left edge, which makes it run once, after the loop.
    • total = total + sub. This reads the old value, adds sub and stores the result back under the same name. After the four passes, total goes 50, 90, 150 and then 195.
    • join is called on the separator. The text before .join goes between the elements, and the elements must all be strings. lines holds only strings, because each row was already built with str().
    • Numbers need str(). Joining items[i] with quantities[i] directly raises a TypeError, because + does not mix text and integers.

    Edge cases and common mistakes

    • An empty cart. With three empty lists, the loop never runs and result is 'Total: $0': the total row is still added.
    • Quantity zero. With items = ["Tea", "Cup"], prices = [4, 7] and quantities = [0, 2], the receipt is Tea x0: $0, Cup x2: $14 and Total: $14. The row for a zero-quantity item still appears.
    • Indenting the total row. Inside the loop it would be appended four times, once per item.
    • Setting total = 0 inside the loop. It would reset on every pass, and the final total would be only the last item's subtotal.
    • Lists of different lengths. The loop uses the length of items. If prices or quantities is shorter, Python raises an IndexError when it reaches the missing position.
    • A missing space or x. The row format is exact: Pants x1: $40, not Pants1: $40.

    Testing

    • The starting lists give five lines ending with Total: $195.
    • ["Pen"], [3], [4] gives Pen x4: $12 and Total: $12.
    • Empty lists give Total: $0.
    • ["Tea", "Cup"], [4, 7], [0, 2] gives Tea x0: $0, Cup x2: $14 and Total: $14.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free