How to Write a While Loop in Python
Learn how to use while loops in Python for repeated execution based on conditions.
While loops execute code repeatedly as long as a condition is true. They’re useful when you don’t know in advance how many iterations you need.
Basic Syntax
count = 0
while count < 5:
print(count)
count += 1
# Output: 0, 1, 2, 3, 4
Comparison with For Loops
# For loop - when you know the iterations
for i in range(5):
print(i)
# While loop - when condition-based
user_input = ""
while user_input != "quit":
user_input = input("Enter command: ")
print(f"You entered: {user_input}")
Using break
Exit the loop early:
while True:
user_input = input("Enter a number (or 'quit'): ")
if user_input == "quit":
break
number = int(user_input)
print(f"Square: {number ** 2}")
print("Goodbye!")
Using continue
Skip to the next iteration:
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue # Skip even numbers
print(count)
# Output: 1, 3, 5, 7, 9
While-Else
The else block runs when the condition becomes false (not on break):
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed normally")
# Output: 0, 1, 2, Loop completed normally
# With break - else doesn't run
count = 0
while count < 3:
if count == 1:
break
print(count)
count += 1
else:
print("This won't print")
# Output: 0
Common Patterns
Countdown Timer
import time
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1
time.sleep(1)
print("Blast off!")
Validating Input
while True:
age = input("Enter your age: ")
if age.isdigit() and int(age) > 0:
age = int(age)
break
print("Please enter a valid positive number")
print(f"Your age is {age}")
Processing a List
items = ["apple", "banana", "cherry"]
while items: # While list is not empty
item = items.pop()
print(f"Processing: {item}")
# Output: cherry, banana, apple
Finding Values
import random
target = 7
attempts = 0
while True:
guess = random.randint(1, 10)
attempts += 1
if guess == target:
print(f"Found {target} in {attempts} attempts!")
break
Avoiding Infinite Loops
# Bad - infinite loop (missing increment)
# count = 0
# while count < 5:
# print(count) # count never changes!
# Good - always update the condition variable
count = 0
while count < 5:
print(count)
count += 1 # Don't forget this!
# Safe pattern with a maximum iterations
max_iterations = 1000
iterations = 0
while some_condition and iterations < max_iterations:
# Do work
iterations += 1
if iterations >= max_iterations:
print("Warning: Maximum iterations reached")
Nested While Loops
outer = 0
while outer < 3:
inner = 0
while inner < 3:
print(f"({outer}, {inner})")
inner += 1
outer += 1
# Output: (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)
Summary
- Use
while condition:for condition-based loops - Use
breakto exit early - Use
continueto skip iterations - Use
elsefor code that runs when loop completes normally - Always ensure the condition will eventually become false
- Use a safety counter for potentially infinite loops