Loops & Iteration

Beginner · 20 min read · ▶ live playground · ✦ checkpoint

One line of code can print one score. A loop can print every score, count every attempt, and keep asking until the program has enough information. Loops are blocks of code that run more than once, and iteration is one pass through a loop.

The while loop

A while loop is a loop that keeps running while its condition is truthy. It feels like a guard at a door: "Keep going while this rule still passes."

energy = 3
 
while energy > 0:
    print(f"Energy: {energy}")
    energy = energy - 1
 
print("Rest")

Energy: 3
Energy: 2
Energy: 1
Rest

Read that slowly. Python checks energy > 0, runs the block, subtracts 1, then goes back to check the condition again. The update line matters because it moves the loop toward stopping.

Use while when you do not know the exact number of repeats yet: while attempts remain, while a password is wrong, while a game is still running.

for loops and iterables

A for loop is a loop that takes one item at a time from an iterable. An iterable is a value Python can step through one item at a time, like a string or a counting sequence.

name = "Ada"
 
for letter in name:
    print(f"Letter: {letter}")
 
print("range(3)")
for number in range(3):
    print(number)
 
print("range(2, 7, 2)")
for number in range(2, 7, 2):
    print(number)

Letter: A
Letter: d
Letter: a
range(3)
0
1
2
range(2, 7, 2)
2
4
6

The name after for is the loop variable, the name Python reassigns to the current item on each pass. In for letter in name, letter first refers to "A", then "d", then "a".

range() is Python's counting tool for loops. It describes numbers for a for loop to walk through:

  • range(stop) starts at 0 and stops before stop.
  • range(start, stop) starts at start and still stops before stop.
  • range(start, stop, step) moves by step each time.

That "stops before" rule is the part that saves you once you learn it and bites you before you do.

Try it — count a tiny basket

Change apples < 3 to apples < 5, then change the range() line. Watch which loop counts by condition and which loop counts by a described sequence.

python — playgroundlive
⌘/Ctrl + Enter to run

Controlling a loop

Sometimes one pass should stop early. Sometimes the whole loop should stop early. Python gives you three small control statements.

break exits the nearest loop immediately. continue skips the rest of the current iteration and starts the next one. pass does nothing; it is a placeholder when Python requires a block and you are not ready to put work there.

marks = "a-b!"
 
for mark in marks:
    if mark == "-":
        continue
    if mark == "!":
        break
    if mark == "b":
        pass
    print(mark)
 
print("Done")

a
b
Done

The dash is skipped by continue. The exclamation point stops the loop with break. The pass line under "b" does nothing, so Python keeps going and prints b.

Loop else

Python also has an else block for loops. A loop else is a block that runs only if the loop finishes without hitting break.

secret = "x"
 
for letter in "maze":
    if letter == secret:
        print("Found token")
        break
else:
    print("No token")

No token

Common patterns

Loops show up in a few shapes again and again:

  • Count a fixed number of times with for and range().
  • Keep going until a condition changes with while.
  • Skip unwanted items with continue.
  • Stop a search as soon as you find the answer with break.
  • Build a running total, a value updated on each iteration to remember the total so far.

A nested loop is a loop inside another loop. Use it when each outer item has its own inner set of work, like rows and seats.

rows = 2
seats = 3
 
for row in range(1, rows + 1):
    for seat in range(1, seats + 1):
        print(f"Row {row}, seat {seat}")

Row 1, seat 1
Row 1, seat 2
Row 1, seat 3
Row 2, seat 1
Row 2, seat 2
Row 2, seat 3

The outer loop chooses a row. For each row, the inner loop walks through every seat. That means the inner work runs rows * seats times, so nested loops can grow fast.

Checkpoint

Answer all three to mark this lesson complete

You now have the last tool Part I needs: repetition. Next, the console game pack puts input, types, conditionals, and loops into small programs that feel like real games.

+50 XP on completion