Basic

Loops and Iteration

Repeat work with for and while loops, and control them with break/continue.

What you will see

2 is prime 3 is prime 4 is not prime 7 is prime

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

Loops repeat work without retyping it. I count forward with range, stop a while loop by changing its own condition, skip and exit iterations mid-run, pair items with their indices, and use the for-else idiom to flag whether a search found a divisor.

1

range(3) hands me 0, 1, 2, start at zero, stop short of the end. I let a for loop walk that sequence and print each number as it comes.

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

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

What it prints
0 1 2
range(3) has three numbers but the last is 2, not 3. Think of it as 'count up to but not including' the number you wrote.
2

A while loop keeps going until its condition is false, so the loop must change that condition itself or run forever. I bump the counter inside the body and print as it climbs to five.

count = 0 while count < 5: print(count) count += 1

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

What it prints
0 1 2 3 4
If the body never changed count, the condition would stay true forever. Every while loop needs a clear way out.
3

Inside a loop I can skip ahead or stop entirely. I print a range, jump past three with continue, and quit before seven with break, then watch which numbers survive the trip.

for i in range(10): if i == 3: continue if i == 7: break print(i)

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

What it prints
0 1 2 4 5 6
continue skips only the rest of the current iteration; break exits the whole loop. They affect the nearest loop only.
4

I rarely need a manual counter anymore. enumerate gives me each item with its position at the same time, so I can print both without juggling a second variable.

for idx, name in enumerate(["a", "b"]): print(idx, name)

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

What it prints
0 a 1 b
enumerate counts from zero by default. Handy for lists, but it starts at 0, so the first position is 0, not 1.
5

A for loop can have its own else that runs only when the loop finished without a break. I use it to check each number for a divisor and print which ones are prime.

for n in [2, 3, 4, 7]: for d in range(2, n): if n % d == 0: print(f"{n} is not prime") break else: print(f"{n} is prime")

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

What it prints
2 is prime 3 is prime 4 is not prime 7 is prime
The for...else else matches the for, not the if. It runs only if no break happened inside.

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 pulls items from an iterator, runs the body, and repeats until exhausted or stopped.
1 Iterator created from collection
↓
2 Next item fetched -> bound to loop variable
↓
3 Body executes -> may mutate state
↓
4 break ends early, continue skips remainder
Why this works
Loop control statements

break exits the nearest loop; continue skips to the next iteration; else on a loop runs only if the loop completed without break:

for n in [2, 3, 4]:
    for d in range(2, n):
        if n % d == 0:
            break
    else:
        print(n, "is prime")

The for...else idiom is handy for search-and-fail scenarios.

When you have a choice

for vs while

Use for when you iterate a known collection or a range. Use while when you loop until a runtime condition changes. A classic while True with break models events like waiting for user input:

while True:
    answer = input("quit? ")
    if answer == "yes":
        break

Every loop needs a clear exit path.

Examples

Iterating with for

Looping over sequences

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

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

range(n) yields 0..n-1; range(start, stop, step) is flexible. for works over any iterable.

While loops

Loop until a condition is false

count = 0
while count < 5:
    print(count)
    count += 1

Always make sure the condition eventually becomes false, or the loop runs forever. Prefer for when the count is known.

break, continue, enumerate

Controlling the loop

for i in range(10):
    if i == 3:
        continue   # skip to next iteration
    if i == 7:
        break      # exit the loop
    print(i)

for idx, name in enumerate(["a", "b"]):
    print(idx, name)   # 0 a / 1 b

enumerate pairs each item with its index, avoiding manual counters.

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.

← Control Flow: Conditionals
Previous Lesson
Control Flow: Conditionals
Next Lesson
Functions
Functions →