Fundamentals

Python For Loops vs While Loops: When to Use Each

Use `for` when iterating over known items or a range. Use `while` when a condition controls how long work continues. Every while loop needs a path to termination.

Step by step

  1. Prefer `for item in items` when visiting collection elements.
  2. Use `range()` for a known number of iterations.
  3. Use `while` for condition-driven retries with a strict limit.
  4. Avoid infinite loops by updating the condition variable.

Run this example

Use Python 3. Copy the code into a file or interactive Python environment.

for number in range(1, 4):
    print(f"for: {number}")
remaining = 2
while remaining > 0:
    print(f"while: {remaining}")
    remaining -= 1

Expected output

for: 1
for: 2
for: 3
while: 2
while: 1

Common issue

If your program never finishes, inspect whether the `while` condition ever becomes false.

Try it yourself

Change the range to print five numbers, then implement a countdown from three.

Pick the stopping rule first

Use a for loop when you already have a collection or range to visit. Use while when repetition depends on a changing condition. A while loop must change the state used by its condition, or it can run forever. range(3) yields 0, 1, 2: the stop value is excluded.

Two ways to repeat

The for loop labels known tasks. The while loop reduces a counter until its condition is false.

tasks = ["read", "run", "change"]
for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")
remaining = 2
while remaining > 0:
    print(f"Attempts left: {remaining}")
    remaining -= 1

Expected output

1. read
2. run
3. change
Attempts left: 2
Attempts left: 1

Filter without changing the source

Build a new list when filtering. Removing items from a list while iterating over it can skip entries. Use continue to skip one iteration and break to exit the loop. Keep indentation consistent because it defines the loop body.

Exercise and troubleshooting

Print only positive numbers from [-2, 0, 3, 5]; the output should be 3 and 5 on separate lines. If a while loop does not end, interrupt it with Ctrl+C and check the state update and comparison. Trace the first three iterations on paper.

Keep learning

Read the relevant documentation · Free foundational resources

Related guides: Python Variables and Data Types Explained With Examples and How to Write Your First Python Automation Script.

Interested in applying these skills to a product? Explore the optional Python to Profit course. It focuses on product and business building, not replacing foundational Python study.