Python While Loops
Learn how to use while loops in Python to repeat code execution based on conditions.
Python Loops
Python has two primitive loop commands:
whileloopsforloops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example - Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example - Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example - Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example - Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")Practical Examples
Countdown Timer
countdown = 5
while countdown > 0:
print(f"Countdown: {countdown}")
countdown -= 1
print("Blast off!")User Input Validation
password = ""
while password != "secret":
password = input("Enter password: ")
if password != "secret":
print("Incorrect password, try again.")
print("Access granted!")Sum of Numbers
total = 0
number = 1
while number <= 10:
total += number
number += 1
print(f"Sum of numbers 1 to 10: {total}")Finding Factors
num = 12
factor = 1
factors = []
while factor <= num:
if num % factor == 0:
factors.append(factor)
factor += 1
print(f"Factors of {num}: {factors}")Infinite Loops
Be careful with while loops! If the condition never becomes false, the loop will run forever:
Example - This will run forever:
i = 1
while i < 6:
print(i)
# i is never incremented, so it will always be 1To avoid infinite loops:
- Always ensure the loop variable is modified inside the loop
- Make sure the condition can eventually become false
- Use a counter or maximum iterations as a safety measure
Example - Safe loop with maximum iterations:
i = 1
max_iterations = 100
iterations = 0
while i < 6 and iterations < max_iterations:
print(i)
i += 1
iterations += 1
if iterations >= max_iterations:
print("Loop stopped due to maximum iterations")Nested While Loops
You can have while loops inside while loops:
Example - Multiplication table:
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"{i} x {j} = {i * j}")
j += 1
print("---")
i += 1While Loop vs For Loop
When to use while loops vs for loops:
Use While Loop When:
- You don't know how many iterations you need
- The loop depends on a condition that may change unpredictably
- You need to loop until user input meets criteria
- You're waiting for an external condition
Use For Loop When:
- You know the number of iterations in advance
- You're iterating over a collection (list, string, etc.)
- You need a counter variable
- You're working with ranges of numbers
break, continue, and else
n = 0
while n < 10:
n += 1
if n == 3:
continue # skip the rest of this iteration
if n == 6:
break # exit the loop entirely
print(n) # prints 1 2 4 5
# a while-else runs only if the loop finished WITHOUT break
x = 0
while x < 3:
x += 1
else:
print("done") # runsAvoid Infinite Loops
Every while needs a condition that eventually becomes false. Forgetting to update the loop variable hangs your program.
# BUG: n never changes -> runs forever
# n = 0
# while n < 5:
# print(n)
# FIX: update the variable
n = 0
while n < 5:
print(n)
n += 1If a program hangs, press Ctrl+C to stop it, then check that your loop variable is being updated toward the exit condition.
Try It Yourself
Exercise 1: Print the numbers 5 down to 1 using a while loop.
Show solution
n = 5
while n >= 1:
print(n)
n -= 1Exercise 2: Keep doubling 1 until it exceeds 100, printing each value.
Show solution
x = 1
while x <= 100:
print(x)
x *= 2 # 1 2 4 8 16 32 64Key Takeaways
whilerepeats while a condition is true — use it when the count is unknown.breakexits,continueskips to the next iteration.- Always move toward the exit condition to avoid infinite loops.
📘 Real-World Deep Dive
<code>while</code> is the right tool when the number of iterations is unknown up front — polling for state, retrying a flaky I/O call, or stepping toward a numeric goal.
Real-Life Scenario
Polling an HTTP endpoint with exponential backoff until it returns 2xx or you give up.
Real-Life Example
import random, time
def flaky_request(simulate):
if random.random() < simulate["fail_rate"]:
return random.choice([500, 503, 504])
return 200
def fetch_with_backoff(simulate, *, max_tries=6):
delay = 0.5
for try_ in range(1, max_tries + 1):
code = flaky_request(simulate)
if 200 <= code < 300:
return code, try_
print(f"try {try_}: got {code}, sleeping {delay:.1f}s")
time.sleep(delay)
delay *= 2 # exponential backoff
return code, max_tries
sim = {"fail_rate": 0.6}
final_code, tries = fetch_with_backoff(sim)
print(f"final code: {final_code}, attempts: {tries}")Expected Output
try 1: got 503, sleeping 0.5s
try 2: got 500, sleeping 1.0s
try 3: got 504, sleeping 2.0s
try 4: got 200, sleeping ...
final code: 200, attempts: 4Common mistakes
- Forget to update the loop variable and you'll spin forever — Python does not warn.
time.sleepis exact in tests but slow; inject a sleep function for unit tests.- Retry loops must always have a hard upper bound (
max_tries) — otherwise an outage wedges the worker.
🚀 Performance & Best Practices
while x:is faster thanwhile x is not None:when the existence is what you mean.- For exponential backoff, jitter avoids "thundering herd" — sleep
delay * random.random(). - When polling, use
asyncio.sleepinstead oftime.sleepso other tasks can run.
🧪 Try It Yourself
- Add jitter to the backoff delay and re-run.
- Cap backoff at 30 s and re-run.
- Replace the loop body with
tenacityorbackofflibrary decorators.