A loop runs a block of code repeatedly so you don't have to copy-paste it. Use a for loop when you know how many times to repeat (or have a collection to walk through), and a while loop when you only know the condition for stopping. Almost every loop bug is one of two things: the loop runs one time too many or too few (an off-by-one error), or its stopping condition can never become false (an infinite loop).

For vs While: How to Choose

for loop while loop
Best when the number of iterations or the collection is known you stop on a condition, not a count
Typical form for i in range(n): / for (int i = 0; i < n; i++) while not done:
Counter handling managed by the loop itself you update it manually
Classic failure off-by-one in the bounds forgetting to update → infinite loop

A useful habit: if you catch yourself writing a while loop with a manual counter that goes from 0 to n, rewrite it as a for loop. The for version has fewer places to make a mistake.

The Three Iteration Patterns You'll Use Constantly

Most real loops are one of these shapes:

Accumulator — build up a result across iterations:

total = 0
for price in prices:
    total += price

Search with early exit — stop as soon as you find what you need:

found = None
for user in users:
    if user.id == target:
        found = user
        break

Transform — produce a new collection from an old one:

squares = []
for x in numbers:
    squares.append(x * x)

Nested loops combine these: an outer loop over rows and an inner loop over columns visits every cell of a grid, at a cost of m×nm \times n iterations — which is why nested loops are the usual source of slow code.

Worked Example 1: Summing 1 to n (and Checking the Answer)

Sum the integers from 1 to 100:

total = 0
for i in range(1, 101):   # range(1, 101) gives 1, 2, ..., 100
    total += i
print(total)              # 5050

Trace the first three iterations: total goes 0 → 1 → 3 → 6. Each pass reads the old value and stores a new one — that's the accumulator pattern.

The closed-form formula lets you verify the loop:

i=1ni=n(n+1)2=1001012=5050\sum_{i=1}^{n} i = \frac{n(n+1)}{2} = \frac{100 \cdot 101}{2} = 5050

If your loop prints 4950, you summed 1 to 99: range(1, 100) stops before 100. That is the single most common off-by-one in Python — range(a, b) includes a but excludes b.

Worked Example 2: The Fence-Post Problem

You're placing fence posts along a 10-meter fence with a post every meter. How many posts? Not 10 — 11, because a fence with nn sections has n+1n + 1 posts.

The same trap appears in code whenever you loop over boundaries instead of segments:

# Print a timeline mark at 0, 1, 2, ..., 10  (11 marks)
for t in range(0, 11):    # not range(0, 10)!
    print(f"mark at {t}")

And in index form: an array of length nn has valid indexes 00 through n1n-1. Both of these are wrong:

for i in range(0, len(arr) + 1):  # IndexError on the last pass
for i in range(1, len(arr)):      # silently skips arr[0]

When a loop bound feels uncertain, test it on a tiny input — an array of length 2 or 3 — and count the iterations by hand. Off-by-one errors survive on big inputs and die instantly on small ones.

While Loops and the Infinite-Loop Trap

A while loop must make progress toward its exit condition on every pass:

n = 1
while n < 1000:
    n = n * 2     # progress: n grows every pass
print(n)          # 1024

Delete the n = n * 2 line and the condition n < 1000 stays true forever. Three checks before you run any while loop:

  1. What makes the condition eventually false?
  2. Does every path through the body move toward that?
  3. What happens on the very first check — does the loop even run once?

The third question matters because a while loop checks before the body. If the condition is false initially, the body runs zero times — sometimes that's correct, sometimes it's the bug.

Common Loop Mistakes

Off-by-one bounds. < vs <=, range(n) vs range(n + 1). Decide whether you're counting items or boundaries (fence posts), then test on a tiny case.

Modifying a collection while looping over it. Removing items from a list inside for item in list: skips elements, because indexes shift under you. Loop over a copy, or build a new list instead.

Resetting the accumulator inside the loop. total = 0 placed inside the body instead of before it makes every answer equal to the last item. Initialization belongs before the loop.

Using break as a band-aid. A break is fine for early-exit searches, but if a loop needs three breaks to terminate, the condition itself is wrong — rewrite it.

From Loops to Everything Else

Loops are the engine under most of what comes next: sorting algorithms are loops with clever swap rules, big-O analysis is mostly counting loop iterations, and recursion is what you reach for when the repetition is self-similar rather than linear. Before moving on, make sure you can write the accumulator, early-exit, and transform patterns from memory — they account for the majority of loops you will ever write.

Frequently Asked Questions

What is the difference between a for loop and a while loop?
A for loop is best when you know how many iterations you need or have a collection to walk through, because it manages the counter for you. A while loop repeats as long as a condition stays true, which fits situations where the number of repetitions is unknown in advance. Any for loop can be rewritten as a while loop, but the for version usually has fewer ways to go wrong.
What is an off-by-one error?
An off-by-one error happens when a loop runs one time too many or one time too few, usually because of a wrong boundary such as using less-than instead of less-than-or-equal, or forgetting that array indexes run from 0 to length minus 1. The classic illustration is the fence-post problem: a fence with 10 sections needs 11 posts. Testing on a tiny input catches these quickly.
How do I avoid an infinite loop?
Make sure every pass through the loop body moves the program toward making the stopping condition false, for example by incrementing a counter or shrinking the remaining input. Before running a while loop, check what makes the condition eventually fail, confirm every branch in the body makes progress, and consider what happens on the very first check.
Can a while loop run zero times?
Yes. A while loop checks its condition before executing the body, so if the condition is false at the start, the body never runs. This is often the correct behavior, such as processing an empty list. Languages like C and Java also offer a do-while loop, which checks the condition after the body and therefore always runs at least once.

Need help with a problem?

Upload your question and get a verified, step-by-step solution in seconds.

Open GPAI Solver →