Home / Journal

Python (Part 5): Loops

Python (Part 5): Loops

In Part 4 we taught our programs to make decisions with if/elif/else. Now let's teach them to repeat — because typing print() a hundred times is nobody's idea of fun.

That's what loops are for. A loop runs the same block of code over and over, so you write the logic once and let Python do the repeating. Python gives you two: the for loop (repeat for each item in a collection) and the while loop (repeat while a condition stays true). Like everything in Python, both lean on the colon and the indented block we met back in Part 1. Let me walk you through them.

The for Loop

A for loop walks through a collection one item at a time. You name a variable, say what to loop over, end the line with a colon :, and indent the body:

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

That prints:

apple
banana
cherry

On each pass, the variable fruit is set to the next item in the list, and the indented block runs once with that value. Python handles the "get the next one, stop at the end" bookkeeping for you — there's no counter to manage and no off-by-one mistakes to make.

The collection doesn't have to be a list. A for loop happily walks over anything Python considers a sequence — including a string, one character at a time:

for ch in "hi":
    print(ch)

That prints h then i. (You'll also loop over dictionaries and other collections later in the series; the shape is always the same.)

Counting with range()

Sometimes you don't have a list — you just want to do something a set number of times. That's what range() is for. It produces a sequence of numbers you can loop over:

for i in range(5):
    print(i)

This prints 0 1 2 3 4 — five numbers. Notice two things that trip up beginners:

  • range() starts at 0, not 1 (Python counts from zero, like most languages).
  • **The end value is excluded.** range(5) gives you 0 through 4 — five numbers, but it stops before 5.

range() takes up to three arguments — start, stop, and step — and only stop is required:

range(2, 6)        # 2, 3, 4, 5      -> start at 2, stop before 6
range(0, 10, 2)    # 0, 2, 4, 6, 8   -> step by 2 (evens)
range(5, 0, -1)    # 5, 4, 3, 2, 1   -> a negative step counts down

So to count from 1 to 5 the way a human would, you write range(1, 6) — start at 1, stop before 6. Once the "stop is excluded" rule clicks, range() becomes second nature.

Note: range() doesn't build the whole list in memory — it hands out the numbers one at a time as the loop asks for them, so range(1000000) costs almost nothing. If you ever want to see the numbers as a list, wrap it: list(range(5)) gives [0, 1, 2, 3, 4].

The while Loop

A while loop repeats as long as a condition stays true — the same kind of condition we wrote in Part 4. Use it when you don't know in advance how many times you'll loop:

n = 3

while n > 0:
    print(n)
    n = n - 1

print("Liftoff!")

This prints 3, 2, 1, then Liftoff!. Before each pass Python checks n > 0; when n finally reaches 0 the condition is false and the loop ends, so execution continues at the (dedented) print below.

That n = n - 1 line is doing the important work: it moves the loop toward its stopping point. Forget to change the variable the condition depends on and you get an infinite loop — the condition never turns false and your program spins forever. If that happens in the terminal, press Ctrl+C to stop it.

Note: rule of thumb — reach for for when you're iterating over a known collection or a fixed count (the common case), and while when you're repeating until some condition changes (waiting for input, retrying, counting down).

Breaking Out and Skipping Ahead

Two keywords give you finer control inside any loop:

  • break stops the loop immediately and jumps past it.
  • continue skips the rest of the current pass and moves straight on to the next one.

Here's break — stop as soon as we hit 3:

for i in range(5):
    if i == 3:
        break
    print(i)

That prints 0 1 2 and then quits the loop — 3 and 4 never print. And here's continue — skip the even numbers:

for i in range(5):
    if i % 2 == 0:
        continue
    print(i)

That prints 1 3 — the % 2 == 0 test catches the evens (remember %, the remainder operator from Part 3), and continue jumps past the print for them. Both keywords work exactly the same inside a while loop.

Getting the Index with enumerate()

A for loop hands you each item, but sometimes you also want to know its position. Instead of managing a counter by hand, wrap the collection in enumerate() and Python gives you both:

for i, fruit in enumerate(["apple", "banana", "cherry"]):
    print(i, fruit)

That prints:

0 apple
1 banana
2 cherry

On each pass enumerate() hands back a pair — the index and the item — which we unpack into i and fruit in one go. It's cleaner and less error-prone than keeping a separate count = 0 variable and bumping it yourself, and it's the Pythonic way to loop "with the index."

To Be Continued…

You can now make your programs repeat work instead of copy-pasting it: for to walk through a collection, range() to count, while to repeat until a condition changes, and break / continue / enumerate() to steer the loop from the inside. Together with the decisions from Part 4, loops are the other half of nearly every useful program.

In Part 6 we'll dig into Python's core data structures — lists, tuples, dictionaries, and sets — the collections you'll spend most of your time looping over. We touched a list already; next we'll see how to index, slice, and organize your data properly. Stay tuned!

← All articles