Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Use a for loop when you want to process each item in an iterable, such as a list or string. Use a while loop when you want to repeat code as long as a condition is true. The key difference is whether your repetition is driven by available items or by a condition.
Use a for loop to process each item
A Python for loop takes items from an iterable one at a time and runs its body for each one. The Python Tutorial puts it this way: “The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.” (Python Tutorial, section 4.2.)
names = ["Ari", "Bo", "Cy"]
for name in names:
print(f"Hello, {name}!")
On each pass, name is bound to the next value: first "Ari", then "Bo", then "Cy". You do not need to create or update a counter just to visit every name. A for loop works with many iterables, not only lists; for example, it can process characters in a string.
Use range() when numbers are the items
When you need a sequence of numbers—for example, to repeat an operation a set number of times—use range():
#1 Best Overall
for number in range(1, 6):
print(number)
This prints 1 through 5. The stop value, 6, is excluded. Likewise, range(5) supplies 0, 1, 2, 3, and 4: five values, not the numbers 1 through 5. You can provide a start, stop, and step, including a negative step for a descending sequence. A range represents an arithmetic progression and supplies its values as you iterate rather than building a list of every value up front. See the Python Tutorial’s discussion of range().
Do not use range(len(items)) by default when the items themselves are what you need. Prefer for item in items. If you need both each item and its position, use enumerate():
Rank #2
for index, name in enumerate(names):
print(index, name)
Use while when a condition controls repetition
A while loop tests a condition and runs its body while that condition is true. The condition is checked before each pass, so a false condition at the start means the body does not run at all.
remaining = 3
while remaining > 0:
print(remaining)
remaining -= 1
Here, remaining -= 1 changes the state that the condition checks. Eventually remaining > 0 becomes false, and the loop ends. The Python language reference specifies how while conditions and loop bodies work.
Free tools Windows power users keep installed
One-click scans. No signup required.
Before writing a while loop, identify what will make its condition false or what deliberate exit will stop it. Some loops intentionally wait for a sentinel value or user action; an accidental loop that never changes its condition may run indefinitely.
Choose the loop that matches the task
| Question | Use | Example |
|---|---|---|
| Do you have items to process, in order? | for |
for name in names: |
| Should repetition continue while a condition stays true? | while |
while remaining > 0: |
| Do you need a numeric progression? | for with range() |
for number in range(1, 6): |
| Do you need an item’s position as well as its value? | for with enumerate() |
for index, name in enumerate(names): |
Stop or skip work with break and continue
Use break to leave a loop as soon as you have what you need. This example stops searching after the first match:
target = "Bo"
for name in names:
if name == target:
print("Found", name)
break
break exits only the innermost enclosing for or while loop. In nested loops, an inner-loop break does not automatically exit the outer loop.
Use continue when you want to skip the rest of the current pass and move on to the next iteration:
Best Value
for number in range(5):
if number == 2:
continue
print(number)
This skips printing 2; the remaining values are still processed. In a while loop, continue returns control to the condition check, so make sure the loop can still make progress rather than repeating the same state forever. The Python language reference defines the behavior of both statements.
Use loop else for normal completion without break
A loop may have an optional else suite. It runs when a for iterator is exhausted or a while condition becomes false. It is skipped if the loop ends with break; a return or raised exception also bypasses it.
target = "Dee"
for name in names:
if name == target:
print("Found", name)
break
else:
print("No match")
In this search, else means no item matched before the loop completed. Indent it at the same level as for, not under the if: the else belongs to the loop, not to the conditional. The Python Tutorial explains this pattern in its sections on loop statements.
Quick Recap
Avoid common loop mistakes
- Expecting the stop value in
range(): the stop endpoint is excluded, sorange(5)ends at 4. - Counting when you can process the item directly: write
for item in itemsunless you genuinely need an index; useenumerate(items)when you need both. - Changing a collection while iterating over it: deleting or adding entries to the same collection during traversal can produce confusing results. The Python Tutorial recommends iterating over a copy or building a new collection instead. Its collection-mutation example shows both approaches.
- Forgetting how a
whileloop ends: check that its condition changes or that a deliberate exit path can occur. - Assuming
breakleaves every nested loop: it exits only the innermost loop. - Reading loop
elseas anifalternative: it belongs to the loop and runs only after normal completion withoutbreak.
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.




