Python for loop vs while loop: when to use each

Both loops repeat code, so beginners often wonder which to pick. The rule of thumb: use a for loop when you know what you are looping over, and a while loop when you are waiting for something to change. Every example below was run, and the output shown is exact.

for with range: a known number of times

range(3) gives 0, 1 and 2. The loop variable takes each value in turn. The end of range is never included.

for i in range(3):
    print(i)

Output:

0
1
2

for over a list: each item

A for loop can walk straight through a list, a string, a dictionary or anything else you can go through one by one. You do not need an index.

for part in ["wrench", "cable"]:
    print(part)

Output:

wrench
cable

while: until something changes

A while loop checks its condition before every turn. Something inside the loop must change that condition, or it never stops. Here the battery drops by 3 until there is not enough left, and you do not know the number of turns in advance.

battery = 10
steps = 0
while battery >= 3:
    battery -= 3
    steps += 1
print(steps)

Output:

3

break and continue

break leaves the loop at once. continue skips the rest of this turn and moves to the next one. Both work in for and in while loops.

for n in range(1, 8):
    if n % 2 == 0:
        continue
    if n > 5:
        break
    print(n)

Output:

1
3
5

The infinite loop

A while loop whose condition never becomes false runs forever. If your program seems stuck, check that the variable in the condition really changes inside the loop. On this site, a program that runs for more than five seconds is stopped for you.

Common questions

Can every for loop be written as a while loop?
Yes, but it is longer and easier to get wrong, because you manage the counter yourself. Prefer for whenever you are going through a collection or a fixed range.
What is the difference between break and continue?
break ends the whole loop. continue only skips the current turn and carries on with the next one.
Why does my while loop never end?
The condition stays true because nothing inside the loop changes the variable it tests. Add a line that moves it toward the end, such as n -= 1.

Practise it