For Loop vs While Loop in Python

The for loop vs while loop in Python choice comes down to one thing: a for loop walks through a sequence or a fixed count, and a while loop keeps repeating until a condition turns false, however many passes that takes.

for item in items:        # you know what you're looping over
    ...

while not done:           # you loop until something changes
    ...

My test machine had Python 3.12.5; each output on this page is pasted from a real Command Prompt session.

For loop vs while loop: the same task written both ways

Here’s one job, adding up weekly sales, done with each loop. Watch how much bookkeeping the while version needs:

weekly_sales = [1250.00, 980.50, 1430.25, 1105.75]

total = 0.0
for amount in weekly_sales:
    total += amount
print(f"for loop total:   ${total:,.2f}")

total = 0.0
i = 0
while i < len(weekly_sales):
    total += weekly_sales[i]
    i += 1
print(f"while loop total: ${total:,.2f}")

Output:

for loop total:   $4,766.50
while loop total: $4,766.50
Command Prompt output of a Python for loop and a while loop adding the same weekly sales list
Both loops print a total of $4,766.50; the while loop just needs a counter to get there.

The while loop creates, tests and bumps i by hand; forget i += 1 and it never ends. If you’re new to lists, see looping through a list in Python.

When should you use a for loop?

Reach for for when there’s something to walk through: a list, file, dict or range(). You don’t manage an index, and enumerate() hands you a position when you want one:

cities = ["Austin", "Denver", "Seattle"]
for rank, city in enumerate(cities, start=1):
    print(rank, city)

for day in range(1, 4):
    print(f"2026-10-{day:02d}: nightly backup done")

Output:

1 Austin
2 Denver
3 Seattle
2026-10-01: nightly backup done
2026-10-02: nightly backup done
2026-10-03: nightly backup done

If you want counting, you use range(), explained in for i in range() in Python. The full syntax lives in my Python for loop guide.

When should you use a while loop?

Use while when you can’t predict the number of passes. This plan deposits $400.00 a month and stops once the balance hits $10,000.00:

balance = 2500.00
deposit = 400.00
month = 0

while balance < 10_000:
    balance = balance * 1.004 + deposit   # 0.4% monthly interest
    month += 1

print(f"Goal reached after {month} months: ${balance:,.2f}")

Output:

Goal reached after 18 months: $10,136.35
Command Prompt output of a Python while loop counting the months until a savings balance reaches 10,000 dollars
The loop works out the month count itself; nobody had to calculate it first.

The Python while loop tutorial covers the basics, and while loops with multiple conditions shows how to combine tests with and and or.

Which is faster in Python, a for loop or a while loop?

For counting, the for loop wins in CPython: range() counts in C, while the while loop runs its test and += as bytecode on every pass. I timed both:

import timeit

def with_for(n=1_000_000):
    total = 0
    for i in range(n):
        total += i
    return total

def with_while(n=1_000_000):
    total = 0
    i = 0
    while i < n:
        total += i
        i += 1
    return total

def with_sum(n=1_000_000):
    return sum(range(n))

print("Same result:", with_for() == with_while() == with_sum())
for f in (with_for, with_while, with_sum):
    best = min(timeit.repeat(f, number=5, repeat=3))
    print(f"{f.__name__:<11} {best:.3f} s for 5 runs")

Output:

Same result: True
with_for    0.162 s for 5 runs
with_while  0.204 s for 5 runs
with_sum    0.049 s for 5 runs
Command Prompt output of Python timeit comparing a for loop, a while loop and sum(range()) over one million numbers
The for loop beats the while loop, and the built-in sum() beats both by a wide margin.

Your times will differ, but the order holds. A built-in beats either loop, as shown in summing list elements in Python.

Avoid infinite loops in a Python while loop

A while loop stops only when its condition turns false or a break runs. while True plus break is the cleanest retry pattern; I used iter() instead of input() so the run repeats exactly:

answers = iter(["abc", "-5", "42"])
attempts = 0

while True:
    attempts += 1
    text = next(answers)
    if text.isdigit() and int(text) > 0:
        print(f"Accepted {text} after {attempts} tries")
        break
    print(f"{text!r} is not a positive number, try again")

Output:

'abc' is not a positive number, try again
'-5' is not a positive number, try again
Accepted 42 after 3 tries
Command Prompt output of a Python while True loop rejecting two bad answers and accepting a positive number
Two bad answers are rejected, and the third, 42, ends the loop on the third try.

Python has no do-while keyword; this is how you write a do-while loop in Python. To skip a pass instead, see continue in a Python while loop.

Keep going with these loop tutorials:

Frequently asked questions

What is the main difference between a for loop and a while loop in Python?

A for loop runs once per item; a while loop runs while its condition is true.

Can every for loop be written as a while loop?

Yes, with a manual index, but the for loop is shorter and safer.

Is a for loop faster than a while loop in Python?

Usually, for counting, because range() counts in C.

When is a while loop better than a for loop?

When the number of passes isn’t known, such as retrying input.

How do I stop an infinite while loop?

Press Ctrl+C. In code, make sure the condition can turn false or a break runs.

Where are for and while documented?

See for statements in the Python tutorial.