03 / REUSABLE LOGIC · LESSON 09

Repeat useful work

Use loops to total values and build a bounded countdown.

11 min · learn at your pace

Visit each item

A for loop assigns each item in a collection to a name, then runs its indented body. Start an accumulator before the loop and update it inside. total += count is a shorter form of total = total + count.

Use range(1, 4) for the integers 1, 2, and 3. The stop value is excluded, just as it is with slices. Iterating directly over records is usually clearer than generating indexes and looking up each record.

Repeat until a condition changes

A while loop checks a condition before each iteration. Something in its body must move the program toward stopping. A countdown that never changes its counter runs forever. In this lab, Stop terminates the worker, and a 30-second active execution limit provides another way out.

break exits a loop; continue moves to the next iteration. Keep these choices explicit so someone reviewing your automation can tell how much work it will do. The countdown here only builds a list; it does not delay execution or retry a real service.

Try an example.py
counts = [2, 4, 1]
total = 0
for count in counts:
    total += count
print(total)
YOUR TURN

Put it into practice.

Use counts = [2, 0, 5, 3] to calculate total_incidents. Build countdown containing 3, 2, 1 in that order, using a counter that stops at zero. Print the total.

See an explained solution
One way to solve it.py
counts = [2, 0, 5, 3]
total_incidents = 0
for count in counts:
    total_incidents += count
countdown = []
remaining = 3
while remaining > 0:
    countdown.append(remaining)
    remaining -= 1
print(total_incidents)

The for loop accumulates counts, including the zero. The while loop changes its own condition on every iteration and stops after three entries.