While loops continue executing as long as a condition remains True. They're perfect for situations where you don't know exactly how many iterations you need.
while condition:
# code to execute
# don't forget to update the condition!- Countdown:
while n > 0: - Input validation:
while not valid_input: - Processing until condition:
while more_data: - Search until found:
while not found:
Always ensure the condition will eventually become False:
# Good - counter decreases
counter = 10
while counter > 0:
counter -= 1
# Bad - infinite loop!
while True:
print("This runs forever")- Use
breakto exit early - Use
continueto skip to next iteration - Consider if a
forloop might be better - Always have a plan for when the loop should end