Python While Loops

A while loop repeats a block of code again and again for as long as its condition stays true.

How a while loop works

A while loop is useful when you do not know in advance exactly how many times you need to repeat something, but you do know the condition under which repetition should continue. Python checks the condition before each pass; while it is true, the indented body runs, and as soon as it becomes false, the loop ends and the program moves on.

Counting with while

count = 1

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

print("Done")
Note: Something inside the loop must eventually make the condition false. In the example, count += 1 does this. Forgetting to update the variable creates an infinite loop that never stops.

Controlling the loop with break and continue

Two keywords give you finer control inside a loop. The break statement exits the loop immediately, ignoring the remaining condition, while continue skips the rest of the current pass and jumps straight back to the condition check for the next one.

break and continue

number = 0

while number < 10:
    number += 1
    if number == 3:
        continue  # skip printing 3
    if number == 7:
        break     # stop the loop entirely
    print(number)
  • break: leaves the loop right away, no matter what the condition says.
  • continue: abandons the current pass and starts the next one.
  • Both are usually paired with an if statement so they trigger only in specific situations.

The else clause on a while loop

Python lets you attach an else block to a while loop. The else runs once, after the loop finishes naturally because its condition became false. If the loop is stopped early by break, the else block is skipped.

while with else

attempts = 0

while attempts < 3:
    print("Attempt", attempts + 1)
    attempts += 1
else:
    print("All attempts used up.")
StatementEffectLoop else runs?
Condition becomes falseLoop ends normallyYes
breakLoop ends immediatelyNo
continueCurrent pass is skippedLoop continues
Note: If a while loop ever seems stuck, you can usually stop a running Python program by pressing Ctrl+C in the terminal. Then review your condition and update logic.

Exercise: Python While Loops

When is a while loop's condition evaluated?