The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Python gives you two loop statements. A for loop repeats over the items of an iterable, and a while loop repeats as long as a condition stays true. Choosing between them comes down to one question: what decides whether the loop runs again? Once you can answer that, the rest of loop control (range(), enumerate(), break, continue, and the loop else clause) follows from the same idea.
Choose a loop by what controls repetition
The examples below follow the Python 3.14 documentation. The core behavior has been stable across Python 3 releases, but the reference pages are the authority if you are on an older interpreter.
A for statement works through the items an iterable supplies. Python evaluates the expression that produces the iterable once, creates an iterator from it, and on each pass assigns the next item to the loop target before running the indented suite. Strings, tuples, lists, and other iterables all work this way. The loop ends when the iterable is exhausted.
A while statement tests an expression before each pass and runs its suite while that expression is true. Use it when the decision to continue depends on a condition that can change inside the loop. You are responsible for making that condition eventually false, unless indefinite repetition is what you intend.
#1 Best Overall
Side-by-side comparison
| Question | for |
while |
|---|---|---|
| What drives the next pass? | The next item from an iterable | A Boolean expression, retested before each pass |
| Typical use | Processing each element of a collection, or a known sequence of numbers | Waiting for a condition, repeating until a value meets a target, or input-driven loops |
| Ends when | The iterable is exhausted | The condition becomes false |
| Risk to watch | Modifying the collection being iterated | A condition that never changes, causing an endless loop |
The distinction is about what determines the next pass, not merely a different spelling of a counted loop. If you find yourself writing a while loop only to increment a counter and compare it to a limit, a for loop over a range() usually reads better.
Looping over numbers with range()
range() produces an arithmetic progression of integers. Its stop value is excluded:
range(5)yields 0, 1, 2, 3, 4.range(1, 6)yields 1 through 5.range(0, 10, 3)yields 0, 3, 6, 9.
A range object supplies values as the loop asks for them. It does not build a list of every number first, so for n in range(1_000_000) does not allocate a million-element list. The official tutorial describes it as an iterable, which is why you can use it directly in a for statement.
Rank #2
Getting the index and the item together
Sometimes a task needs both the position and the value. The tutorial’s own question here is how to iterate over the indices of a sequence. Its answer is range() combined with len(), and then it notes that enumerate() is more convenient in most such cases. Use enumerate() when you need both, and loop directly over the sequence when you do not need indices:
names = ["Ada", "Grace", "Linus"]
for index, name in enumerate(names):
print(index, name)
Output:
0 Ada
1 Grace
2 Linus
Accumulating a result
When a loop builds a result, keep the changing state in a variable that exists before the loop starts, and update it on each pass:
total = 0
for number in range(1, 6):
total += number
print(total)
This prints 15. The same pattern works with a while loop when the stopping point is not known in advance, for example summing values until the total passes a threshold:
total = 0
number = 1
while total < 20:
total += number
number += 1
print(total)
Here the loop stops when total reaches 21, the first running total that is at least 20. The condition is the thing that changes, so while is the natural fit.
Controlling a loop with break, continue, and else
break exits the nearest enclosing for or while loop immediately. continue skips the rest of the current pass and moves on to the next item, or to the next condition check in a while loop.
Recommended Free Tools
Both loop forms accept an else suite. It is easiest to read as “run this if the loop was not stopped by break.” It runs in two cases:
- A
forloop has exhausted its iterable. - A
whileloop ends because its condition became false.
It is skipped when break exits the loop. A return or an unhandled exception also leaves the loop without running it. Do not read loop else as an if–else pair; it has no condition of its own.
The tutorial demonstrates the most common use, searching for a value and reporting when nothing was found:
for n in range(2, 10):
for factor in range(2, n):
if n % factor == 0:
print(n, "equals", factor, "*", n // factor)
break
else:
print(n, "is a prime number")
Here the inner else runs only for values of n where the inner loop never hit break, meaning no factor was found.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsBest Value
Predicting what a loop will do
Trace the control flow in this order when you read an unfamiliar loop:
- Identify the controlling expression: an iterable for
for, a Boolean expression forwhile. - Check whether anything inside the suite changes that expression, or the collection being iterated.
- For each pass, note whether a
continueskips the rest of the body. - Note whether a
breakcan exit the loop. If it can, theelsesuite will not run on that path. - After the loop, remember that a
fortarget keeps the last value it was assigned, and that an empty iterable never assigns it.
Changing a collection while looping over it
The tutorial warns that modifying a collection while iterating over that same collection can be tricky. This is a specific caution about changing the collection being iterated, and it does not mean every change inside a loop is unsafe. Two strategies avoid the problem: iterate over a copy of the collection, or build a new collection with the items you want.
numbers = [1, 2, 3, 4, 5, 6]
kept = []
for number in numbers:
if number % 2 == 0:
kept.append(number)
print(kept)
This prints [2, 4, 6]. Building a new list keeps the loop simple and makes the result explicit.
Assigning to the loop target inside the suite does not change which item the iterator supplies next. On each pass, the for statement assigns the next item from the iterator, regardless of what you did to the name in the previous pass.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Further reading
The two primary references are the official tutorial chapter, More Control Flow Tools, and the language reference section on compound statements. The tutorial is the better starting point; the reference is the place to check exact behavior of condition testing and loop termination. A beginner Python book can also help with practice exercises, though none is required to learn loops from these references.
Quick Recap
“
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




