Advanced

Loops & iteration

Repeat actions automatically with for and while loops, avoiding repeated code.

What you will see

break at 3: 1 2 skip 2: 1 3

The full result is shown at the end of the exercise below.

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

A loop repeats a body while a condition holds. I add up numbers with a FOR loop, play rounds in a WHILE loop, and use break and continue to leave or skip a run, watching exactly how each keyword changes the output.

1

I add up a list with a FOR loop. The body runs once per item, growing the total, then I print the sum so I never repeat the addition by hand.

numbers = [10, 20, 30] total = 0 for n in numbers: total = total + n print(total)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
60
A FOR loop runs once for every item, so the total counts all of them, add each value exactly once.
2

I play rounds in a WHILE loop. The body runs while lives stay above zero, counting down each pass, then prints game over when the loop finally ends on its own.

lives = 3 while lives > 0: print("Play round") lives = lives - 1 print("Game over")

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Play round Play round Play round Game over
Always change something inside a while loop, or the condition never becomes false and it runs forever.
3

I control a loop mid-run. break leaves as soon as the value matches, and continue skips just that value, so I see how each keyword changes which numbers actually print.

print("break at 3:") for n in [1, 2, 3, 4, 5]: if n == 3: break print(n) print("skip 2:") for n in [1, 2, 3, 4]: if n == 2: continue print(n)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
break at 3: 1 2 skip 2: 1 3 4
break exits the loop entirely; continue skips only the current pass. Nesting them too deeply makes loops hard to follow.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A loop repeats its body while a condition holds, updating state each pass until it stops.
1 Check the loop condition
↓
2 True -> run the body
↓
3 Update the variable that controls the loop
↓
4 Repeat until the condition is false
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

numbers = [10, 20, 30] sets nothing on screen
total = 0 sets nothing on screen
for n in numbers: sets nothing on screen
total = total + n sets nothing on screen
print(total) 60
Why this works
Breaking and continuing

Two keywords control a loop mid-way:

  • break: leave the loop immediately.
  • continue: skip to the next iteration.

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break       # stop at 3
    print(n)         # 1, 2

for n in [1, 2, 3, 4]:
    if n == 2:
        continue    # skip 2
    print(n)         # 1, 3, 4

Use them to skip work, but avoid nesting them too deeply.

When you have a choice

for vs while

Use for when you know how many times to loop (over a list or range). Use while when you loop until a condition changes.

# for: known count
for i in range(3):
    print(i)   # 0, 1, 2

# while: unknown count
while not solved:
    solved = try_solve()

Both are interchangeable, but matching the loop to the job makes code clearer.

Examples

A for loop over a list

Adding up numbers

numbers = [10, 20, 30]
total = 0
for n in numbers:
    total = total + n
print(total)  # 60

Why it works: the loop body runs once per item, so you never write the same line three times.

A while loop with a stop condition

Looping until a condition fails

lives = 3
while lives > 0:
    print("Play round")
    lives = lives - 1
print("Game over")

Watch out: if the condition never becomes false, the loop runs forever. Always change something inside a while loop.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Conditionals & branching
Previous Lesson
Conditionals & branching
Next Lesson
Debugging strategies
Debugging strategies →