Python lesson
Loops, step 2
Step by step: total starts at 0. Round 1 adds 96, so total is 96. Round 2 adds 120: 216. Round 3 adds 175: 391. The last print isn't indented, so it runs once, after the loop.
Try this lesson free →Example
A loop can build up an answer. Start a total at 0, then add each item as the loop visits it:
sales = [96, 120, 175]
total = 0
for s in sales:
total = total + s
print(f"Added {s}, total is now {total}")
print(f"Final: {total}")Added 96, total is now 96
Added 120, total is now 216
Added 175, total is now 391
Final: 391Key points
total = 0Before the loop: start at zero.
total = total + sInside the loop: the new total is the old total plus this item.
After the loopUn-indented lines run once the loop has finished.
This is what sum() does for you. Writing it yourself shows how a loop builds an answer one step at a time.
Practice
1. Build the line inside the loop that adds each sale to total.
total = total + s2. Build the line that starts the count at zero.
count = 03. Add up the qty list with a loop (not sum), then print the total.
qty = [2, 1, 3, 1, 4]
total = 0
for q in qty:
total = total + q
print(total)4. Count how many orders there are with a loop (not len), then print the count.
orders = [70, 15, 24, 35, 140]
count = 0
for o in orders:
count = count + 1
print(count)5. Add up every sale doubled (each sale times 2) with a loop, then print the total.
sales = [96, 120, 175]
total = 0
for s in sales:
total = total + s * 2
print(total)Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →