While Loops
Unlike for loops, while loops are non-deterministic – the program (and programmer!) doesn't
always know how many times the loop will repeat before it finally calls it quits. Instead, it
depends on a particular condition – usually waiting for a boolean
to flip from True to False. 🕵️♂️
Danger
If the condition never becomes False, an infinite loop can be created. If you encounter
an infinite loop, usually Ctrl+C will kill the program (for basic scripting).
(Don't worry, it happens to everyone! Even the pros forget to escape sometimes. 🏃♂️💨)
The basic form of a while loop is:
The expression is evaluated at the start of each loop, and if it is True, the loop will run.
It's like a party that keeps going as long as the music is playing! 🎶
For example:
| Loop Until "Exit" | |
|---|---|
Until the user enters "exit", this loop will keep echoing the user input infinitely. Careful not to get stuck in an infinite loop.
Tip
It is possible that a while loop will never run if, when it is reached, the condition
it checks is already False. 🚫
Another common pattern is to check equality and increment/decrement the value on each iteration:
| Loop Until Value is Zero | |
|---|---|
The while True Pattern
One of the most common patterns is while True with an explicit break to exit. This is
perfect when you don't know up front how many iterations you'll need:
| While True with Break | |
|---|---|
This reads as: "Keep looping forever, until we explicitly break out." It's cleaner than managing a separate boolean flag in many cases.
Input Validation Loop
A classic use case — keep asking until the user gives valid input. Like a barista who won't let you leave without confirming your order. ☕
Validation Pattern
The pattern is: loop forever, continue on bad input (to retry), break on good input.
Simple and effective. 🎯
Sentinel Value Pattern
Sometimes you loop until you encounter a special "sentinel" value that signals the end:
| Sentinel Value | |
|---|---|
Common sentinel values include 0, -1, empty string "", or None.
Processing Until Exhausted
While loops excel when you're consuming from a source until it's empty:
| Processing a Stack | |
|---|---|
Returns:
Working on: Test
(Tasks remaining: 3)
Working on: Deploy
(Tasks remaining: 2)
Working on: Review PR
(Tasks remaining: 1)
Working on: Write code
(Tasks remaining: 0)
All done! 🎉
Retry with Limits
Don't let your program try forever — add a maximum attempt count:
The else Clause
Just like for loops, while loops can have an else clause. It runs only if the loop
completes normally (without a break). See Controlling Loops
for more.
Waiting for a Condition
While loops are great for polling or waiting:
Intentional Infinite Loops
Some programs should run forever — like servers, game loops, or monitoring scripts:
| Game Loop (Conceptual) | |
|---|---|
| Simple Server Loop (Conceptual) | |
|---|---|
Breaking Out of Infinite Loops
During development, if you accidentally create an infinite loop:
- In a terminal: Press
Ctrl+Cto send a keyboard interrupt - In an IDE: Use the stop/kill button
- As a last resort: Force quit the process
This happens to everyone. It's practically a rite of passage. 🎓
for vs while: When to Use Each
Use for when... |
Use while when... |
|---|---|
| Iterating over a known sequence | Number of iterations is unknown |
| Processing each item in a collection | Waiting for a condition to change |
| Counting a specific number of times | Input validation loops |
Using enumerate() or zip() |
Implementing retry logic |
| The loop should end naturally | You need while True with break |
Key Takeaways
| Concept | What to Remember |
|---|---|
| Basic while | while condition: — loops while condition is True |
| while True | Common pattern with explicit break |
| Input validation | Loop with continue (retry) and break (success) |
| Sentinel values | Special value that signals end of input |
| Retry with limits | Add a counter to prevent infinite attempts |
| else clause | Runs if loop completes without break |
| Infinite by design | Some programs (servers, games) intentionally run forever |