Reading preferences
Concept

Repeating Steps with Loops

Repeat actions with for and while, and control when an iteration ends.

python, for, while, loops, break, continue

Repeat a small job

To count books on a shelf, look at each one and add one to a running total. A loop repeats instructions without writing the same instruction many times. A for loop visits items from an iterable, such as a list or range. A while loop repeats while its condition is true.

Follow a for loop

ItemTotal beforeTotal after
202
426
369

The indented body runs once per item. An empty list causes zero iterations. range(3) supplies 0, 1, 2; its stop is excluded.

Python illustration

total = 0
for value in [2, 4, 3]:
    total = total + value
print(total)

count = 3
while count > 0:
    print(count)
    count = count - 1

Prepared output — not live execution:

9
3
2
1

The while loop stops because count decreases to zero. A condition that never changes can make a loop run indefinitely.

Other loop controls

break leaves the nearest loop; continue skips the rest of the current iteration and starts the next. pass is an instruction that does nothing: it can stand in for a block while developing, but does not stop or skip a loop. A nested loop puts one loop inside another, such as visiting each seat within each row. The inner loop starts again for each outer iteration.

for row in range(2):
    for seat in range(3):
        if seat == 1:
            continue
        if row == 1 and seat == 2:
            break
        print(row, seat)

Prepared output — not live execution:

0 0
0 2
1 0

For each row, seat 1 is skipped. In row 1, break leaves the inner loop when seat 2 is reached. The outer loop would continue to another row if there were one. To see the difference, replacing continue with pass would do nothing at that point: the rest of the inner body would still run.

See the reasoning

Follow the example one step at a time

Follow the lesson's running total, then see continue and break in a nested loop. This is a prepared teaching demonstration, not live code execution.

Start

values: [2, 4, 3]
total: 0

Before the loop, the running total is zero.

Think about empty inputs, stopping conditions, and whether a nested loop does more work than necessary. List traversal gives a related DSA view.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Which numbers does range(3) provide?
2. What can happen if a while condition never becomes false?
3. What does break do inside a loop?
4. What does continue do?

References and further reading