AnyCompiler
← Blog

September 15, 2026

for Loop vs. while Loop in Python: When to Use Each

Python has two loop types, and it's genuinely common to be unsure which one fits a given situation — the short version is that they answer two different questions.

for loops: when you know what you're iterating over

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output
apple
banana
cherry

Use a for loop when you're processing a known, finite collection — a list, a range of numbers, the characters in a string. You already know, at least in principle, how many times it'll run.

while loops: when you're waiting for a condition

attempts = 0
while attempts < 3:
    print(f"Attempt {attempts + 1}")
    attempts += 1
Output
Attempt 1
Attempt 2
Attempt 3

Use a while loop when the number of iterations isn't known ahead of time — waiting for valid user input, retry logic, or processing until some condition becomes true or false. The loop above happens to run a fixed number of times, but the condition (attempts < 3) is what actually controls it, not a predetermined count.

The practical rule

If you can name the thing you're looping over — a list, a range, a string — reach for a for loop. If you're looping until something becomes true or false, reach for a while loop.

See the for Loops and while Loops lessons in our free Python course for the full details on range(), break, and each loop type's syntax.