Python While Loops

A Python while loop repeats a block of code as long as its condition stays True. It is the right choice when you do not know in advance how many times the loop should run, such as waiting for a value to reach a target.

A Basic while Loop

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

print("Done")
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done

The line count += 1 is essential. Without it, count would stay at 1 forever and the loop would never end. This is called an infinite loop; in a terminal you can stop one with Ctrl+C.

Loop Until a Goal Is Reached

Here we do not know how many years it takes for savings to double, so a while loop is a natural fit.

savings = 1000
rate = 0.08
years = 0

while savings < 2000:
    savings *= 1 + rate
    years += 1

print(f"{years} years, final amount {savings:.2f}")
10 years, final amount 2158.92

The break Statement

break exits the loop immediately. A common pattern is while True with a break inside, which runs until some condition inside the loop is met.

n = 1

while True:
    if n * n > 50:
        break
    n += 1

print("First number whose square is over 50:", n)
First number whose square is over 50: 8

The continue Statement

continue skips the rest of the current pass and jumps back to the condition. Here it skips the multiples of 3.

i = 0

while i < 10:
    i += 1
    if i % 3 == 0:
        continue
    print(i, end=" ")
1 2 4 5 7 8 10 

The end=" " argument tells print() to put a space after each value instead of a new line, so all numbers appear on one line.

The while else Clause

A loop can have an else block. It runs when the loop ends normally, but not when it is stopped by break. This is handy for search loops.

numbers = [4, 8, 15, 16]
i = 0

while i < len(numbers):
    if numbers[i] % 2 == 1:
        print("Found an odd number:", numbers[i])
        break
    i += 1
else:
    print("No odd numbers")
Found an odd number: 15

while vs for

  • Use for when you loop over a known collection or range
  • Use while when you loop until a condition changes
  • Always make sure something inside a while loop eventually makes the condition False, or calls break

Frequently asked questions

How do I stop an infinite loop in Python?

Press Ctrl+C in the terminal to interrupt it. To prevent one, make sure the loop variable changes on every pass, or include a break.

What is the difference between break and continue?

break ends the whole loop immediately. continue only skips the rest of the current iteration and moves on to the next one.

Does Python have a do-while loop?

No. Use while True: with the body first and an if ... break at the end to get the same behaviour.