The while Loop
Repeat code as long as a condition stays True.
Syntax
while condition:
...The while loop repeats as long as its condition is True. Use it when you do not know in advance how many times you will loop.
Avoid infinite loops
Make sure something inside the loop eventually makes the condition False, or it will run forever. Usually you update a counter or a flag.
Example
count = 3
while count > 0:
print(count)
count -= 1
print('Liftoff!')
# Output:
# 3
# 2
# 1
# Liftoff!When to use it
- A game loop keeps running until the player's health drops to zero or they choose to quit.
- A retry mechanism attempts a network request up to five times, stopping when it succeeds.
- A menu program keeps prompting the user for input until they enter a valid choice.
More examples
Basic while loop
Runs the loop body as long as count is at most 5, incrementing each iteration.
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5While with a sentinel value
Loops until a sentinel value (-1) is encountered, accumulating a sum along the way.
total = 0
values = [10, 20, -1, 30] # -1 signals stop
idx = 0
while values[idx] != -1:
total += values[idx]
idx += 1
print('Sum:', total) # Sum: 30while/else pattern
Uses the while/else clause to detect whether the loop completed without a break.
attempts = 0
success = False
while attempts < 3:
attempts += 1
if attempts == 2: # simulate success
success = True
break
else:
print('All attempts failed')
if success:
print(f'Succeeded on attempt {attempts}') # Succeeded on attempt 2
Discussion