While Loops
While for loops iterate over sequences, while loops repeat as long as a condition is True. They're ideal when you don't know in advance how many iterations you'll need — like waiting for user input or processing until a condition changes.
Basic While Loop
The syntax mirrors an if statement, but the code repeats:
count = 5
while count > 0:
print(count)
count = count - 1
print("Blast off!")
Output:
5
4
3
2
1
Blast off!
The loop checks the condition before each iteration. When count reaches 0, the condition count > 0 becomes False, and the loop stops.
The Danger of Infinite Loops
A while loop runs forever if its condition never becomes False. This is called an infinite loop:
# DON'T RUN THIS - infinite loop!
while True:
print("Forever...")
Always ensure something inside your loop eventually makes the condition False. If you accidentally create an infinite loop, press Ctrl+C in your terminal to stop it.
Breaking Out Early
The break statement exits a loop immediately, regardless of the condition:
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print("You typed:", answer)
print("Goodbye!")
This pattern — while True with a break — is common when you want to check the exit condition in the middle of the loop rather than at the beginning.
Skipping Iterations
The continue statement skips the rest of the current iteration and jumps to the next:
count = 0
while count < 10:
count = count + 1
if count % 2 == 0:
continue # Skip even numbers
print(count) # Only prints odd numbers
When to Use While vs For
Use for when you're iterating over a known sequence or counting a specific number of times. Use while when you're waiting for a condition to change and don't know how many iterations that will take.
# For: known iterations
for i in range(10):
process(i)
# While: unknown iterations
while not connection_established:
try_connect()