The request

From Jennifer Castillo, Support Team Lead
Your goal
Set result to the cart total as a float: the sum of quantity times price for each position in quantities and prices, rounded to 2 decimals.
- Store a number in
resultnot done yet
Your code
Loading the editor…
Reference solution
Mote checks your result
Press Run. Each row that matches the goal becomes a firefly in your lantern.
What Jennifer gets, and why
The lesson
Repeating work with for
A for loop runs the same block of code once for every item in a list:
prices = [49.99, 129.00, 12.50]
for price in prices:
print(price)
On each pass, the loop variable (price) holds the next item. The indented lines are the loop
body. When the list runs out, the loop ends and Python continues with the first unindented line.
The accumulator pattern
The most common loop in analysis code adds things up. You create a variable before the loop, then update it on every pass:
total = 0
for price in prices:
total += price # same as total = total + price
After the loop, total is 191.49. The same pattern counts things (count += 1), finds the
largest value so far, or builds up a new list with append.
Looping over two lists together
Here quantities and prices sit in separate lists that line up by position. zip pairs them:
quantities = [2, 1, 4]
prices = [49.99, 129.00, 12.50]
list(zip(quantities, prices))
# [(2, 49.99), (1, 129.0), (4, 12.5)]
You can unpack each pair straight into two loop variables:
total = 0
for qty, price in zip(quantities, prices):
total += qty * price
This reads almost like English: for each quantity and price, add the line total. If the lists have
different lengths, zip stops at the shorter one without an error, so make sure your data lines
up before trusting the result.
When you need the position
enumerate gives you the index alongside each item, which helps when you want to label lines:
for i, price in enumerate(prices, start=1):
print(f"Line {i}: ${price:.2f}")
Avoid the older style for i in range(len(prices)): with prices[i] inside. It works, but zip
and enumerate are clearer and harder to get wrong.
Don’t forget the built-ins
When you only need a plain sum of a list, sum(prices) is simpler than a loop. Loops earn their
place when each step does some work first, such as multiplying by a quantity or skipping bad rows.
Common mistakes
- Putting
total = 0inside the loop. It resets on every pass, so you end up with only the last line. - Forgetting to indent the body. Python raises
IndentationErroror, worse, runs the line once after the loop ends. - Rounding inside the loop. Round the final total once.
A look ahead
In pandas you’ll rarely write this loop: (df["quantity"] * df["unit_price"]).sum() does the same
thing for a whole column at once, and much faster. But knowing what that line does under the hood
makes it far easier to debug.
Lantern lit!
Practised: for loopaccumulatorzip
- Solved
- No hints
- First run
