Lesson focus · 8 min read

Python Loop Exercises: Five Patterns That Cover Most Beginner Problems

Most beginner loop problems are variations of five patterns. Learn to recognise the pattern first, then write the loop. That is faster than starting from a blank line and hoping the syntax arrives.

Pattern 1: visit every item

Use for item in items when you need each value and do not care about its position. Name the variable after the item. Print it, transform it, or pass it to a function.

orders = ["latte", "mocha", "tea"]
for order in orders:
    print(order)

Iteration

Pattern 2: repeat a fixed number of times

range(stop) gives 0 through stop - 1. range(start, stop) gives a custom starting point. range(start, stop, step) skips values. Convert a range to a list when you want to inspect it.

print(list(range(3)))
print(list(range(2, 6)))
print(list(range(0, 6, 2)))

Three range shapes

Pattern 3: accumulate a total

Create the accumulator before the loop, update it inside, and use it after. The same pattern works for a sum, a count, or a list of results. Initialising inside the loop is the most common mistake.

prices = [4.5, 6.0, 3.25]
total = 0
for price in prices:
    total += price
print(total)

Accumulation

Patterns 4 and 5: filter and build

Filtering keeps only some items; building collects a result. Both use an if statement or an append inside the loop. Start with the simple loop, then shorten it with a comprehension only after the loop is correct.

prices = [4.5, 6.0, 3.25]
expensive = []
for price in prices:
    if price >= 4:
        expensive.append(price)
print(expensive)

Filtering into a new list

A loop debugging checklist

When a loop behaves unexpectedly, check four things in order: the starting value, the indentation, the boundary, and the update. Print the accumulator once before the loop and once after it. If the result is zero, the body may not run. If it grows too fast, an update may be inside an extra iteration.

total = 0
for n in range(1, 4):
    total += n
    print("inside", n, total)
print("after", total)

Trace the accumulator

Your practice checklist

Common questions

Why does my loop only print the last value?

The print is probably outside the loop, or the result variable is being reassigned instead of accumulated. Check the indentation and the starting value.

When should I use a while loop?

Use while when you do not know the number of repetitions in advance, such as reading until a valid value appears. For a collection or a known range, for is usually clearer.

Are list comprehensions required?

No. Write the loop first. A comprehension is a shorter alternative when the loop is simple enough to read at a glance.

Practice loops

Twelve loop questions with answers and explanations.

Open practice

Keep reading: