Phase 1 · FoundationsModule 6~32 min read

Loops

Repeat work with for and while loops, and iterate elegantly with enumerate and zip.

What you'll learn

Computers excel at repetition. Loops run a block of code again and again — over a list, a range of numbers, or until a condition changes. Python's loops are especially elegant, and this module makes them second nature.

By the end you'll be able to:

  • Loop over any collection with for
  • Generate number sequences with range()
  • Repeat until a condition changes with while
  • Control loops with break and continue
  • Loop with an index using enumerate(), and pair lists with zip()
  • Nest loops for grids and patterns

The for loop

Python's for loop is a "for each" loop — it walks directly through the items of any collection, handing you one at a time. There's no manual index or counter (unless you want one), which makes it clean and hard to get wrong:

for = 'for each item'

A collection

["a", "b", "c"]

──▶

for item in ...

item = "a", then "b", then "c"

for_loop.py
for i in range(5):        # 0, 1, 2, 3, 4
    print(i, end=" ")
print()

for fruit in ["apple", "banana", "cherry"]:   # iterate directly!
    print(fruit)

Tip

Notice you can loop straight over a list of strings — no list[i] indexing needed. This is a big difference from C-style languages, and it's the Pythonic way to iterate.

range()

When you do want to loop a certain number of times, range() generates a sequence of numbers. It takes up to three arguments — range(start, stop, step) — and the stop value is excluded:

ranges.py
print(list(range(5)))         # [0, 1, 2, 3, 4]
print(list(range(2, 8)))      # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2)))  # [0, 2, 4, 6, 8]  (step of 2)

Note

range() is lazy — it doesn't build the whole list in memory, it produces numbers on demand. That's why range(1_000_000) is instant and memory-light. We wrapped it in list() above just to see the values.

The while loop

A while loop repeats as long as its condition stays true. Use it when you don't know the number of repetitions in advance. The golden rule: something inside must eventually make the condition false, or it loops forever:

while_loop.py
count = 3

while count > 0:
    print(count)
    count -= 1        # MUST change, or the loop runs forever

print("Liftoff!")

break & continue

Two keywords give you fine control. break stops the loop completely; continue skips just the current pass and moves to the next:

break vs continue

break

Exits the loop entirely and moves on.

continue

Skips the rest of this pass and starts the next.

break.py
for n in range(2, 10):
    if n == 4:
        continue      # skip only 4
    if n == 7:
        break         # stop the whole loop at 7
    print(n, end=" ")

Note

Python has a rare feature: a loop can have an else clause that runs only if the loop finished without hitting a break — handy for search loops ("did we find it?").

enumerate() & zip()

Two built-ins make loops even nicer. enumerate() gives you the index and the value on each pass — no manual counter. zip() walks several lists together, pairing up their items:

enumerate_zip.py
names = ["Sara", "Omar", "Aisha"]

for i, name in enumerate(names):        # index + value together
    print(i, name)

scores = [90, 85, 100]
for name, score in zip(names, scores):  # walk two lists in step
    print(f"{name}: {score}")

Tip

If you ever find yourself writing for i in range(len(items)): just to index a list, reach for enumerate() instead — it's cleaner and more Pythonic.

Nested loops

A loop can live inside another. For every single pass of the outer loop, the inner loop runs completely — exactly what you need for grids, tables, and patterns:

nested.py
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end=" ")
    print()               # newline after each row

Recap & quick check

Key takeaways

  • Python's for loop is a 'for each' — iterate directly over any collection, no manual index.
  • range(start, stop, step) generates numbers lazily; stop is excluded.
  • while repeats while a condition is true — make sure something changes it.
  • break exits the loop; continue skips to the next pass.
  • Use enumerate() for index + value, and zip() to walk lists together.

Quick check

1. How does Python's for loop work?

2. What does range(2, 8) produce?

3. What does continue do?

4. Which built-in gives you both the index and the value while looping?

5. What does zip() do?

Fantastic — you can now automate repetitive work. Next up: Module 7 — Functions, where you'll package code into reusable building blocks.