BBampaa

Lessons › Python

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. print(total) isn't indented, so it runs once, after the loop, and shows 391.

Try this lesson free →
About 5–10 minutes · no sign-up needed

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(total)

Output:

391

Key points

total = 0Before the loop: start at zero.
total = total + sInside the loop: the new total is the old total plus this item.
count = count + 1To count instead of add up: add 1 each time round, whatever the item is.
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

Try each one in your head first, then open the answer.

1. Build a loop that adds up the sales, then shows the total.
for s in sales:
    total = total + s
print(total)
2. Build a loop that counts the orders, then shows the count.
for o in orders:
    count = count + 1
print(count)
3. 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 →
About 5–10 minutes · no sign-up needed