Pythonwhile Loops

while Loops

A while loop repeats a block of code for as long as a condition stays true, checking that condition before every iteration. Where for is the natural choice when you're iterating over a known collection, while is the natural choice when the number of iterations isn't known ahead of time — you're waiting for some condition to change, not walking through a fixed set of items.

Basic syntax

Basic while loop

Python
count = 0

while count < 5:
    print(count)
    count += 1
# 0
# 1
# 2
# 3
# 4
Infinite loops and break

while True: creates a loop that never stops on its own — it relies entirely on a break statement somewhere inside to exit. This pattern is common when the exit condition is easier to express in the middle of the loop body than up front in the while line itself.

while True with a break condition

Python
import random

attempts = 0
target = random.randint(1, 10)

while True:
    attempts += 1
    guess = random.randint(1, 10)  # simulate a guess
    if guess == target:
        print(f'Found {target} after {attempts} attempts')
        break
    if attempts >= 100:
        print('Giving up after 100 attempts')
        break
The while...else clause

Just like for loops, while loops support an else clause. It runs when the loop's condition becomes false naturally — but is skipped if the loop was exited via break. Conceptually it's identical to for...else: else means "the loop was not interrupted."

while...else

Python
numbers = [4, 8, 15, 16, 23, 42]
target = 99
index = 0

while index < len(numbers):
    if numbers[index] == target:
        print(f'Found {target} at index {index}')
        break
    index += 1
else:
    print(f'{target} was not found in the list')
# 99 was not found in the list
Common pattern: sentinel-controlled loops

A sentinel value is a special marker that signals "stop looping" — commonly used when reading a stream of input until the user types something like "quit".

Sentinel-controlled loop

Python
entries = []

while True:
    command = input('Enter an item (or "quit" to finish): ')
    if command.lower() == 'quit':
        break
    entries.append(command)

print(f'You entered {len(entries)} items: {entries}')
Common pattern: input-validation loops

Validation loops re-prompt the user until they provide acceptable input, only moving on once the value passes whatever check you need.

Re-prompt until valid input

Python
age = None

while age is None:
    raw = input('Enter your age: ')
    if raw.isdigit() and int(raw) > 0:
        age = int(raw)
    else:
        print('Please enter a positive whole number.')

print(f'Thanks, you are {age} years old.')
Infinite loop bugs: forgetting to update the condition
The most common `while` loop bug is forgetting to update the variable the condition depends on, leaving the loop with no way to ever become false. Always double check that every path through the loop body moves the condition toward completion.

Buggy vs fixed

Python
# Buggy: count is never changed, so count < 5 is always true.
# This would spin forever if actually run.
#
# count = 0
# while count < 5:
#     print(count)
#     # forgot: count += 1

# Fixed: the loop variable is updated on every iteration.
count = 0
while count < 5:
    print(count)
    count += 1  # <-- this line is what makes the loop terminate
  • while condition: checks the condition before every iteration.

  • while True: combined with break is the standard way to write "loop until something happens."

  • while...else runs its else block only when the loop condition became false naturally, not via break.

  • Sentinel-controlled loops stop when a special marker value (like "quit") is seen.

  • Input-validation loops re-prompt until the input passes a check.

  • Always make sure something inside the loop body moves the condition toward becoming false — otherwise you get an infinite loop.