Python While Loop
Repeat a block of code as long as a condition is True.
Basic syntax
Python
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
print("Done!")
# Output: Count: 1, 2, 3, 4, 5, then Done!
Avoid infinite loops
Make sure the loop condition will eventually become False. Forgetting to update the counter (
count += 1) is the most common cause of infinite loops.
break — exit immediately
Python
count = 0
while True: # intentional infinite loop
count += 1
if count == 5:
break # exit the loop
print(count) # 5
continue — skip to next iteration
Python — print only odd numbers
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue # skip even numbers
print(n) # 1, 3, 5, 7, 9
while-else
Python
n = 2
while n < 100:
if n % 7 == 0:
print(f"Found: {n}")
break
n += 1
else:
print("Not found") # runs only if loop completed WITHOUT break
Common patterns
Python — wait for valid user input
while True:
user_input = input("Enter a positive number: ")
if user_input.isdigit() and int(user_input) > 0:
break
print("Invalid. Try again.")
print(f"You entered: {user_input}")