A cashier sums line-item costs as items are scanned.
What You Need to Understand
A running total starts from an appropriate identity value, usually zero for addition, and is updated once for each element. The intermediate values can reveal how an accumulation works.
When to Use It
A cashier sums line-item costs as items are scanned.
Step-by-Step Python Example
prices = [3.5, 2.0, 4.5]
running_total = 0
for price in prices:
running_total += price
print(f"Subtotal: {running_total:.2f}")
How the Example Works
The subtotal is updated and displayed after each price; the final total is 10.00.
Example Output
Subtotal: 3.50
Subtotal: 5.50
Subtotal: 10.00
10
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
distances = [2, 5, 3]
total = 0
for distance in distances:
total += distance
print(total)
Important Behavior and Edge Cases
Do not reset the accumulator inside the loop. For currency amounts, integer cents or Decimal is preferable to binary floats.
Try It Yourself
Track a cumulative distance from a list of trip segments.
Common Beginner Mistakes
- Do not reset the accumulator inside the loop. For currency amounts, integer cents or
Decimalis preferable to binary floats. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- A running total starts from an appropriate identity value, usually zero for addition, and is updated once for each element.
- The subtotal is updated and displayed after each price; the final total is 10.00.
- Do not reset the accumulator inside the loop.