While loops
Repeat code as long as a condition is true
A while loop keeps repeating as long as a condition is True. Use it when you don't know in advance how many times to repeat: keep asking until the answer is valid, or keep chatting until the user says goodbye.
How a while loop works
count = 1
while count <= 3:
print(f"Round {count}")
count = count + 1
print("Done!")Before every round, Python checks the condition count <= 3. If it's True, the body runs. If it's False, the loop ends and Python moves on to the next line after the loop.
The three parts of a while loop
- Set up a variable before the loop (
count = 1). - Check it in the condition (
while count <= 3). - Update it inside the body (
count = count + 1), so the condition eventually becomesFalse.
False and the loop runs forever. This is called an infinite loop. Press Ctrl + C in the terminal to stop it.Counting with a while loop
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1 # same as countdown = countdown - 1
print("Lift off!")Looping until something happens
This is where while really shines. The loop stops based on what happens, not on a fixed count.
balance = 1000
years = 0
while balance < 2000:
balance = balance * 1.07 # 7% growth per year
years += 1
print(f"It takes {years} years to double your money.")Asking until the input is valid
password = ""
while len(password) < 8:
password = input("Choose a password (8+ characters): ")
print("Password accepted!")while True with break
Sometimes it's easiest to write a loop that runs "forever" and to leave it with break when you're done. This is the standard pattern for menus and chatbots.
while True:
command = input("Type a command (or 'quit'): ").strip().lower()
if command == "quit":
print("Goodbye!")
break
print(f"You typed: {command}")while True, always double-check that there is a reachable break. See Break, continue, and pass for more ways to control loops.Looping while a list has items
An empty list counts as False, so you can loop until a list is used up.
queue = ["task A", "task B", "task C"]
while queue:
current = queue.pop(0) # take the first item
print(f"Working on {current}")
print("Queue empty!")for or while?
| Feature | for loop | while loop |
|---|---|---|
| Best when | You know what to loop over | You loop until a condition changes |
| Example | Every item in a list | Until the user types quit |
| Counter needed | No (range handles it) | Yes, you update it yourself |
| Risk of infinite loop | No | Yes |
Both loops below print 1 to 5. The for version is shorter, so prefer it when you know the count.
for i in range(1, 6):
print(i)
i = 1
while i <= 5:
print(i)
i += 1Common mistakes
- Forgetting to update the variable in the condition, which creates an infinite loop.
- Updating it in the wrong direction (for example
count += 1when the condition iscount > 0). - Using
=instead of==in the condition:while answer = "yes"is a syntax error. - Forgetting to set up the variable before the loop, which raises a
NameError.
What's next?
Now learn how to stop a loop early, skip a round, or leave a placeholder with break, continue, and pass.