While Loops and Breaking Out
So far, we have seen for loops. A for loop is excellent when you want to process every item in a collection.
But what if you do not know how many times something needs to happen?
For example:
"Keep waiting until the bus arrives."
You do not know whether the bus will arrive in 2 minutes, 10 minutes, or 30 minutes.
This is where the while loop becomes useful.
What Is a while Loop?
A while loop repeats a block of code as long as a condition is true.
The basic structure is:
while condition: do_something()Read it like English:
"While this condition is true, keep doing this."
For example:
count = 1while count <= 5: print(count) count = count + 1Output:
1
2
3
4
5
Python checks the condition before each repetition.
The Bus Stop Analogy
Imagine you are waiting at a bus stop.
Your rule is:
"While the bus has not arrived, keep waiting."
You might mentally repeat:
Has the bus arrived?
↓
No → Keep waiting
↓
Check again
↓
Has the bus arrived?
↓
No → Keep waiting
↓
Check again
↓
Yes → Stop waiting
That is exactly the mental model of a while loop.
bus_arrived = Falsewhile bus_arrived == False: print("Waiting for the bus...")However, this example has a problem.
The value of bus_arrived never changes, so the loop would continue forever.
We need something to eventually change the condition.
Avoiding Infinite Loops
Consider:
count = 1while count <= 5: print(count)What happens?
count is always 1.
Therefore:
count <= 5
always remains true.
The loop never ends.
This is called an infinite loop.
A safer version is:
count = 1while count <= 5: print(count) count = count + 1Now count changes:
1 → 2 → 3 → 4 → 5 → 6
When it becomes 6, the condition:
count <= 5
becomes false.
The loop stops.
The Anatomy of a while Loop
Look at:
count = 1while count <= 5: print(count) count = count + 1There are three important parts:
1. Starting value
count = 12. Condition
while count <= 5:3. Update
count = count + 1The update is extremely important because it moves the loop toward its ending condition.
A useful mental model is:
Start
↓
Check condition
↓
Run body
↓
Update state
↓
Check condition again
while Loop Flow
flowchart TD
A["Start"] --> B["Check while condition"]
B -->|True| C["Execute loop body"]
C --> D["Update values / state"]
D --> B
B -->|False| E["Exit loop"]
The loop keeps traveling around this cycle until the condition becomes false.
What Is break?
Sometimes you want to stop a loop immediately, even if the loop condition is still true.
Python provides the break statement.
Think about the bus stop again.
Your rule might be:
"Wait until the bus arrives."
The moment the bus arrives, you stop waiting.
In Python:
while True: bus_arrived = check_bus() if bus_arrived: break print("Waiting...")The break statement immediately exits the loop.
break in a Simple Example
count = 1while count <= 10: print(count) if count == 5: break count = count + 1Output:
1
2
3
4
5
Why did it stop at 5?
Because when count became 5, this condition became true:
if count == 5:Then:
breakimmediately ended the loop.
A while Loop With break
flowchart TD
A["Start"] --> B["while condition"]
B -->|True| C["Execute loop body"]
C --> D{"Break condition?"}
D -->|Yes| E["break"]
E --> F["Loop ends"]
D -->|No| G["Update state"]
G --> B
B -->|False| F
This is useful when the loop has a normal condition but you also have a special situation that should force it to stop.
What Is continue?
continue is different from break.
breakmeans stop the entire loop.continuemeans skip the rest of the current iteration and move to the next iteration.
Imagine checking a list of students.
Suppose you want to print only students who are present.
If a student is absent, you might say:
"Skip this student and check the next one."
That is the idea behind continue.
Example:
count = 0while count < 5: count = count + 1 if count == 3: continue print(count)Output:
1
2
4
5
When count becomes 3, continue skips the print statement for that iteration.
break vs continue
| Statement | Meaning |
|---|---|
break | Leave the loop completely |
continue | Skip the current iteration |
Think:
break → "I'm done!"
continue → "Skip this one!"
When Should You Use while?
Use a while loop when repetition depends on a condition rather than simply processing a known collection.
Examples include:
- Keep asking for a password until it is correct.
- Keep waiting until a task finishes.
- Keep playing a game while the player has lives.
- Keep accepting input while the user has not chosen to quit.
For example:
password = ""while password != "python123": password = input("Enter password: ")print("Access granted")The loop continues until the condition becomes false.
A Useful Beginner Pattern
Many while loops follow this pattern:
setupwhile condition: work updateFor example:
count = 1while count <= 3: print("Learning Python") count = count + 1Remember:
A while loop asks a question before every repetition.
Key Takeaways
- A
whileloop repeats while a condition is true. - The condition is checked before each iteration.
- Make sure something eventually changes so the loop can stop.
- An infinite loop happens when the stopping condition is never reached.
breakexits the loop immediately.continueskips the current iteration and moves to the next one.- Use
whilewhen you do not necessarily know how many repetitions are required.
Beginner rule: For a
whileloop, always ask yourself: "What will eventually make the condition false?"