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
- Create
lines. An empty list that will hold the rows. - Create
totalat 0. A running total always starts at zero, before any item is counted. - Loop over positions.
for i in range(len(items))makesitake the values 0, 1, 2, 3 for this data. - Compute
sub. It isprices[i] * quantities[i]: this item's price times its quantity. - Add
subtototal. After the last pass,totalholds the sum of every subtotal. - 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 throughstr(). - Append the total row after the loop. This line is not indented, so it runs once.
- 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, andrange(4)produces 0, 1, 2 and 3, soiis 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. Thelines.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, addssuband stores the result back under the same name. After the four passes,totalgoes 50, 90, 150 and then 195.joinis called on the separator. The text before.joingoes between the elements, and the elements must all be strings.linesholds only strings, because each row was already built withstr().- Numbers need
str(). Joiningitems[i]withquantities[i]directly raises aTypeError, because+does not mix text and integers.
Edge cases and common mistakes
- An empty cart. With three empty lists, the loop never runs and
resultis'Total: $0': the total row is still added. - Quantity zero. With
items = ["Tea", "Cup"],prices = [4, 7]andquantities = [0, 2], the receipt isTea x0: $0,Cup x2: $14andTotal: $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 = 0inside 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. Ifpricesorquantitiesis shorter, Python raises anIndexErrorwhen it reaches the missing position. - A missing space or
x. The row format is exact:Pants x1: $40, notPants1: $40.
Testing
- The starting lists give five lines ending with
Total: $195. ["Pen"],[3],[4]givesPen x4: $12andTotal: $12.- Empty lists give
Total: $0. ["Tea", "Cup"],[4, 7],[0, 2]givesTea x0: $0,Cup x2: $14andTotal: $14.
