Beginner 11 min

Loops and counters

Follow a Python loop one iteration at a time and see when the counter stops.

While loop
counter.py
count = 0
while count < limit:
count += 1
print(count)
CURRENT STATE
00
11
22
33
44
55
Count 0Limit 5
Initialize the counter

Set count to zero before checking the loop condition.

Step 1 / 13

Choose the loop

Use for to visit each value in a sequence or iterable. Use while to repeat while a condition stays true. In a while loop, identify which update makes the condition eventually turn false.

How it works

Trace the loop with two columns, one for the item and one for the running result. Start with the result before the loop. For each repetition, write the item and then the new result. With an empty iterable, the loop body runs zero times and the starting result is all you get.

Trace a counter

The diagram and sample start count at zero and advance it by one until count < limit turns false. The update runs five times for a limit of five. In the exercise, you will use a separate accumulator to add a sequence of numbers.

Code example

count = 0
limit = 5
while count < limit:
    count += 1
    print(count)

Check your understanding

Compute the sum of the whole numbers from 1 up to and including the input number.

See the example and explanation
Example 1
Given 3
Answer 6
Example 2
Given 0
Answer 0

Use range(1, limit + 1) and start with a total of zero. For limit 3 the loop adds 1, then 2, then 3. No iterations are needed for limit 0.

Open practice problem
Next lessonLists, indexes, and copies