OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Loops, counting and stopping

Repeat work over a sequence without losing track of what changes each time.

Lesson 8 of 22 · About 20 minutes · Beginner · English

By the end of this lesson

Use for, range and a bounded while loop.

Before you start

  • Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
  • Complete lesson 7 in this route, or be comfortable with its examples.

Three words to know

Iteration
One pass through a loop.
Accumulator
A value updated as items are processed.
Loop condition
The rule deciding whether a while loop continues.

1. Iterate over values

A for loop visits each item. The body runs once per item; statements after it run after the loop finishes. An empty list causes zero iterations, so initialise totals before the loop.

Count pagesPYTHON · save as lesson.py, then run with your interpreter
sizes = [2, 3, 1]
total = 0
for size in sizes:
    total += size
print(total)
What you should see · example output
6

2. Keep positions readable

range stops before its end value. enumerate pairs each value with an index; start=1 makes human-facing numbering convenient. It does not change the list or its actual zero-based indices.

Number a checklistPYTHON · save as lesson.py, then run with your interpreter
for step in range(1, 4):
    print(step)
for number, item in enumerate(["read", "test"], start=1):
    print(f"{number}. {item}")
What you should see · example output
1
2
3
1. read
2. test

3. Make the stopping rule visible

A while loop checks its condition before every pass. This countdown changes the same value used by the condition, so it terminates. If a practice loop runs endlessly, press Ctrl+C in the terminal and check which value should have changed. Avoid editing a list while iterating over that same list; build a separate result instead.

A bounded countdownPYTHON · save as lesson.py, then run with your interpreter
remaining = 3
while remaining > 0:
    print(remaining)
    remaining -= 1
print("done")
What you should see · example output
3
2
1
done

YOUR TURN

A small check before you continue

Sum the numbers from 1 through 5 using a loop. Which range includes 5?

Show a suggested answer

Start total at 0 and add each value from range(1, 6). The sum is 15. range(1, 5) stops at 4.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.