Unlike a for loop, which iterates a predetermined number of times over a known iterable, a while loop keeps running as long as its condition stays true, making it the right tool when the number of iterations isn't known in advance — like waiting for user input, polling until a resource is ready, or processing a queue until it's empty. If the condition never becomes falsy and nothing inside the loop breaks out, it runs forever, producing an infinite loop.
1Understanding while Loop
Unlike a for loop, which iterates a predetermined number of times over a known iterable, a while loop keeps running as long as its condition stays true, making it the right tool when the number of iterations isn't known in advance — like waiting for user input, polling until a resource is ready, or processing a queue until it's empty. If the condition never becomes falsy and nothing inside the loop breaks out, it runs forever, producing an infinite loop.
Deliberate infinite loops are a common, valid pattern — they're typically combined with a break statement inside the body once some internal condition is met, rather than expressing the exit condition in the while line itself.
count = 0
while count < 3:
print(count)
count += 12Practical Example
Here is a real-world application of while Loop showing how it is used in production Python code.
import random
random.seed(1)
attempts = 0
while True:
attempts += 1
roll = random.randint(1, 6)
if roll == 6:
break
print(f"Got a 6 after {attempts} attempts")3Best Practices
Follow these guidelines when working with while Loop:
1. Make sure something inside the loop body actually changes the condition's truth value, to avoid an accidental infinite loop
2. Use a deliberate infinite loop with an internal break for loops whose exit condition is easier to express partway through the body than up front
3. Prefer a for loop over a range when the number of iterations is actually known ahead of time, since it more clearly signals that intent
Tip: Deliberate infinite loops are a common, valid pattern — they're typically combined with a break statement inside the body once some internal condition is met, rather than expressing the exit condition in the while line itself.
count = 0
while count < 3:
print(count)
count += 1