Python While Loops
1. What is a While Loop?
A while loop runs a block of code repeatedly as long as a condition is True.
x = 0
while x < 5:
print(x)
x += 1
# Output: 0 1 2 3 4
Syntax
while <condition>:
# code runs while condition is True
2. For Loop vs While Loop
| For Loop | While Loop | |
|---|---|---|
| Use when | You know how many times to loop | You don't know how many times to loop |
| Loops based on | A range or collection | A condition |
# These do the same thing:
for x in range(5): # for loop
print(x)
x = 0 # while loop equivalent
while x < 5:
print(x)
x += 1
Use a for loop when the number of iterations is known. Use a while loop when it depends on a condition at runtime.
3. Practical Use Case — Validating User Input
A while loop shines when you don't know how many times a user will enter invalid input.
num = input("Enter an integer: ")
while not num.isdigit():
num = input("Enter an integer: ")
This keeps asking until the user gives a valid integer — something a for loop can't easily do.
4. Infinite Loops & break
A while True loop runs forever unless you break out of it.
while True:
num = input("Enter an integer: ")
if num.isdigit():
break # exits the loop as soon as valid input is given
⚠️ Infinite loop warning: If you use
while Trueand neverbreak, your program will crash. Always make sure there's a reachable exit condition.
5. break and continue
Work exactly the same as in for loops.
break — exit the loop immediately
while condition:
if something:
break # stops the loop entirely
continue — skip to the next iteration
while condition:
if something:
continue # skips the rest of this iteration
6. Iterating Through a List with While
lst = [2, 3, 3, 2, 1]
result = 0
i = 0
while result < 9:
num = lst[i]
result += num
print(num)
i += 1
⚠️ Index Out of Range Bug
If the condition is never met, i can exceed the list length and cause a crash.
# ❌ Crashes if values never sum to 9
while result < 9:
...
# ✅ Add a second condition to guard against it
while result < 9 and i < len(lst):
...
Always guard against going out of bounds when iterating a list with a while loop.
7. While-Else Statement
The else block runs only if the loop ended normally (i.e. the condition became False without hitting break).
lst = [2, 3, -2, 4]
target = -2
i = 0
while i < len(lst):
if lst[i] == target:
print("Found it!")
break
i += 1
else:
print("Didn't find it.")
breakhit →elseis skipped- Loop finishes normally →
elseruns
Same behavior as
for-else. Avoids needing afound = Falseboolean flag.
8. Common Mistakes
Forgetting to increment the iterator
i = 0
while i < len(lst):
print(lst[i])
# ❌ forgot i += 1 → infinite loop!
Not guarding against index out of range
# ❌ will crash if condition is never met
while result < 9:
result += lst[i]
i += 1
# ✅ guard with a second condition
while result < 9 and i < len(lst):
result += lst[i]
i += 1
Cheat Sheet
# Basic while loop
while condition:
# body
# Infinite loop with break
while True:
if exit_condition:
break
# Loop with compound condition
while x < 10 and i < len(lst):
...
# While-else
while condition:
if found:
break
else:
# runs only if break was never hit
# Loop control
break # exit the loop entirely
continue # skip to the next iteration