Beginner · 10 min
Totals in a loop
Accumulate a running total while processing a list.
Keep a running total
Set a total to zero before the loop. Add each item to it inside the loop. Resetting the total inside the loop would lose earlier additions.
prices = [4, 7, 2]
total = 0
for price in prices:
total = total + price
print(total)Output
13
Add only matching items
+= adds to the current value. Combine a loop with an if to include only the items you want. Indent the addition inside the condition.
prices = [4, 7, 2]
total = 0
for price in prices:
if price >= 4:
total += price
print(total)Output
11
Totals in a loop
- Write the total after each iteration.
- Keep the initial value outside the loop.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Total a basket
Add all values in prices using a loop. Save the sum in total and display it once after the loop.
Start at zero and use total += price inside the loop.