Python Loops, For vs While, With Examples You Can Run
A beginner's guide to Python's for and while loops, including break, continue, and the loop else clause, with every example runnable in python3.
Once you can write a single line of code, the next real milestone is getting code to repeat itself without you retyping it. Python gives you two main tools for this, the for loop and the while loop, and the official Python tutorial explains exactly how each one works and when to reach for which.
The for loop: when you know what you're iterating over
A for loop in Python is different from the "count from 1 to 10" style loop you may have seen described in other languages. The official tutorial explains: "Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence." You are not managing a counter yourself; you are handing Python a collection and letting it walk through each item.
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
Running this prints each word followed by its length: cat 3, window 6, defenestrate 12. There is no manual counter variable anywhere in this code; Python handles the iteration itself.
Using range() to loop a specific number of times
When you do want the classic "repeat this N times" behavior, Python's built-in range() function generates exactly the sequence of numbers you need:
for i in range(5):
print(i)
This prints 0, 1, 2, 3, 4, one per line. The official tutorial is specific about the boundary: "The given end point is never part of the generated sequence," so range(5) produces five values (0 through 4), not six. You can also give range() a starting point and a step:
print(list(range(5, 10))) # [5, 6, 7, 8, 9]
print(list(range(0, 10, 3))) # [0, 3, 6, 9]
The while loop: when you don't know how many times you'll repeat
A while loop repeats as long as a condition stays true, which makes it the right tool when you do not know in advance how many iterations you will need, for example repeatedly asking a user for input until they give you something valid.
count = 5
while count > 0:
print(count)
count -= 1
print("done")
This prints 5, 4, 3, 2, 1, then "done." The loop keeps running as long as count > 0 stays true, and stops the moment that condition becomes false. Unlike a for loop over a known sequence, nothing here tells Python in advance how many times the loop will run; it is entirely determined by the condition.
break and continue: controlling a loop from the inside
Both loop types support two keywords for changing their normal behavior mid-loop. The official tutorial defines break as exiting "the innermost enclosing for or while loop" immediately, and continue as moving straight to "the next iteration of the loop" without running the rest of the current iteration's code.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} equals {x} * {n // x}")
break
Run this and you will see output like 4 equals 2 * 2, 6 equals 2 * 3, 8 equals 2 * 4, 9 equals 3 * 3. As soon as the inner loop finds any number x that divides evenly into n, it prints the factorization and immediately exits the inner loop with break, rather than continuing to check the remaining values of x.
for num in range(2, 10):
if num % 2 == 0:
print(f"Found an even number {num}")
continue
print(f"Found an odd number {num}")
This prints one line for every number 2 through 9. When num is even, continue skips straight to the next number without running the final print line in that same iteration, which is why each even number only gets one line of output, not two.
The loop's own else clause (a genuinely confusing Python feature)
Python allows a for or while loop to have its own else clause, which runs only if the loop finished normally, without being stopped early by a break. The official tutorial's own example uses this to detect prime numbers:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is a prime number')
Running this prints "2 is a prime number," "3 is a prime number," "4 equals 2 * 2," "5 is a prime number," "6 equals 2 * 3," "7 is a prime number," "8 equals 2 * 4," and "9 equals 3 * 3." The else block only runs for the numbers where the inner loop never found a factor and so never hit break, which is exactly the definition of a prime number. The official tutorial notes a key detail: this else belongs to the for loop, not to the if statement nested inside it, which is the single most common source of confusion with this feature.
Choosing between for and while
- Use a
forloop when you are iterating over a known collection (a list, string, or range) and you know in advance roughly how many items you are working through. - Use a
whileloop when the stopping condition depends on something that happens during the loop itself, like user input, a calculation result, or an external event, and you cannot know the number of iterations ahead of time. - Use
breakto exit a loop early once you have found what you were looking for, avoiding unnecessary additional iterations. - Use
continueto skip the rest of the current iteration's code without exiting the whole loop.
Key takeaways
- A Python
forloop iterates directly over the items of a sequence (list, string, or range) rather than managing a manual counter yourself. range(n)generates numbers from 0 up to but not including n;range(start, stop, step)lets you customize the starting point and increment.- A
whileloop is the right choice when you do not know in advance how many iterations you need, since it depends only on a condition staying true. breakexits a loop immediately;continueskips to the next iteration without running the remaining code in the current one.- A loop's
elseclause runs only if the loop completed without hitting abreak, which the official tutorial uses to elegantly detect prime numbers.