AnyCompiler

while Loops

A while loop keeps running as long as its condition stays true. Use it when you don't know in advance how many times you'll need to loop — unlike a for loop over a list, where the number of iterations is fixed from the start.

count = 0
while count < 5:
    print(count)
    count += 1
Output
0
1
2
3
4

That count += 1 line matters — forget it and the condition never becomes false, and you've written an infinite loop. Always make sure something inside the loop actually moves you toward the condition becoming false.

Exiting early with break

break immediately exits the loop, regardless of the condition. It's common to write while True (a loop that would otherwise never stop) and rely entirely on a break inside it to end things.

count = 0
while True:
    if count == 3:
        break
    print(count)
    count += 1
Output
0
1
2

Notice 3 never gets printed — break exits the moment count == 3 becomes true, before that iteration's print() runs.

Next: functions — packaging code into something you can call by name instead of repeating it.

Practice exercise

Write a while loop that prints numbers starting from 0 and stops with break as soon as the number reaches 4 (so it prints 0, 1, 2, 3).