While Loops
A while loop repeats a block of code as long as a condition is true.
Basic Structure
count = 1
while count <= 5:
print(count)
count = count + 1
Output:
1
2
3
4
5
Note: The indented code runs repeatedly until the condition becomes False.
Infinite Loops with while True
Use while True: to create a loop that runs forever (until you break out of it):
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print("You typed: " + answer)
The break statement immediately exits the loop.
The break Statement
Use break to exit a loop early:
count = 1
while count <= 10:
print(count)
if count == 5:
print("Stopping early!")
break
count = count + 1
Output:
1
2
3
4
5
Stopping early!
The continue Statement
Use continue to skip to the next iteration:
count = 0
while count < 5:
count = count + 1
if count == 3:
continue # skip printing 3
print(count)
Output:
1
2
4
5
Input Validation Example
A common use of while loops is to keep asking until the user gives valid input:
color = ""
while color != "red" and color != "blue":
color = input("Pick red or blue: ")
print("You picked " + color)
Game Loop Example
Many games use while True: as their main loop:
health = 100
while True:
print("Health: " + str(health))
action = input("Attack or run? ")
if action == "run":
print("You escaped!")
break
elif action == "attack":
health = health - 10
if health <= 0:
print("Game over!")
break
Common Mistakes
Forgetting to update the loop variable
# Wrong - infinite loop!
count = 1
while count <= 5:
print(count)
# Oops, forgot to increase count
# Right
count = 1
while count <= 5:
print(count)
count = count + 1
Forgetting the colon
# Wrong
while count <= 5
print(count)
# Right
while count <= 5:
print(count)
Incorrect indentation
# Wrong - print is not inside the loop
while count <= 5:
print(count)
# Right
while count <= 5:
print(count)