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
count = 0
while count < 5:
print(count)
count += 1
# 0
# 1
# 2
# 3
# 4Infinite 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
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')
breakThe 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
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 listCommon 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
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
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.')Buggy vs fixed
# 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 terminatewhile condition:checks the condition before every iteration.while True:combined withbreakis the standard way to write "loop until something happens."while...elseruns itselseblock only when the loop condition became false naturally, not viabreak.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.