Lesson 17: while Loops (Repeating Until Done)
Learn how to write while loops, set conditions, update variables, avoid infinite loops, and understand when to use while vs for with common patterns.
Introduction
In the last lesson, you learned for loops — they process every item in a list.
But sometimes you don't have a list. Sometimes you need to repeat something until a condition changes.
Keep processing revisions until the design is approved. Count down floors until you reach ground level. Ask for input until the user provides valid data.
This is what while loops do. They repeat as long as a condition is true.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Writing while loops
- Loop conditions
- Updating variables inside loops
- Avoiding infinite loops
- When to use while vs for
- Common while loop patterns
Basic while Loop
A while loop repeats as long as its condition is true.
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
print("Done")
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done
The loop checks the condition before each iteration. When it becomes false, the loop stops.
The Syntax
while condition:
# code block (indented)
# this repeats while condition is True
Key parts:
while— keyword that starts the loopcondition— must be True for loop to continue:— colon required- Indented block — code that repeats
How It Works
Python checks the condition before each iteration.
floor = 3
while floor > 0:
print(f"Floor {floor}")
floor -= 1
print("Ground level")
Step 1: Is floor > 0? Yes (3 > 0). Print "Floor 3", floor becomes 2 Step 2: Is floor > 0? Yes (2 > 0). Print "Floor 2", floor becomes 1 Step 3: Is floor > 0? Yes (1 > 0). Print "Floor 1", floor becomes 0 Step 4: Is floor > 0? No (0 is not > 0). Exit loop Continue: Print "Ground level"
Output:
Floor 3
Floor 2
Floor 1
Ground level
Updating the Condition
The loop must eventually make the condition false. Otherwise, it runs forever.
This works (condition changes):
revision = 0
while revision < 5:
revision += 1
print(f"Revision {revision}")
The condition eventually becomes false when revision reaches 5.
This doesn't work (infinite loop):
revision = 0
while revision < 5:
print(f"Revision {revision}")
# revision never changes - infinite loop!
Without updating revision, the condition stays true forever. The loop never ends.
Infinite Loops
An infinite loop runs forever because its condition never becomes false.
# Infinite loop - don't run this!
count = 1
while count > 0:
print(count)
count += 1 # count keeps growing, always > 0
To stop an infinite loop: Press Ctrl+C in the terminal.
Always make sure your loop has a way to exit.
Architectural Example: Processing Revisions
revision = 0
status = "Draft"
while status != "Approved" and revision < 10:
revision += 1
print(f"Creating revision {revision}...")
# Simulate approval after 5 revisions
if revision >= 5:
status = "Approved"
print(f"Final status: {status} after {revision} revisions")
Output:
Creating revision 1...
Creating revision 2...
Creating revision 3...
Creating revision 4...
Creating revision 5...
Final status: Approved after 5 revisions
The loop continues until the status is approved OR we hit 10 revisions (safety limit).
while vs for
Use for loops when:
- You have a list to process
- You know how many iterations you need
- You're iterating through a collection
rooms = ["Office 1", "Office 2", "Office 3"]
for room in rooms:
print(room)
Use while loops when:
- You repeat until a condition changes
- You don't know how many iterations you'll need
- The loop depends on external factors
floor = 10
while floor > 0:
print(f"Floor {floor}")
floor -= 1
In practice: You'll use for loops 90% of the time. while loops are for specific situations.
Common Patterns
Pattern 1: Countdown
floor = 5
while floor >= 0:
if floor == 0:
print("Ground floor")
else:
print(f"Floor {floor}")
floor -= 1
Pattern 2: Processing Until Valid
# Simulate checking if data is valid
attempts = 0
max_attempts = 3
valid = False
while not valid and attempts < max_attempts:
attempts += 1
print(f"Attempt {attempts}")
# Simulate validation
if attempts == 2:
valid = True
print("Data validated")
if not valid:
print("Validation failed after maximum attempts")
Pattern 3: Building Up to a Target
current_area = 0
target_area = 1000
room_size = 150
while current_area < target_area:
current_area += room_size
print(f"Current total: {current_area}m²")
print(f"Target of {target_area}m² reached")
Output:
Current total: 150m²
Current total: 300m²
Current total: 450m²
Current total: 600m²
Current total: 750m²
Current total: 900m²
Current total: 1050m²
Target of 1000m² reached
Real Architectural Workflows
Example 1: Sheet Revision Counter
sheet_number = "A-101"
revision = 0
max_revisions = 5
print(f"Processing {sheet_number}")
while revision < max_revisions:
revision += 1
print(f" Revision {revision}: In progress")
print(f" Final: Revision {revision} issued")
Output:
Processing A-101
Revision 1: In progress
Revision 2: In progress
Revision 3: In progress
Revision 4: In progress
Revision 5: In progress
Final: Revision 5 issued
Example 2: Floor-by-Floor Processing
current_floor = 10
target_floor = 0
print("Descending floors:")
while current_floor > target_floor:
print(f" Processing floor {current_floor}")
current_floor -= 1
print(f"Reached floor {target_floor}")
Output:
Descending floors:
Processing floor 10
Processing floor 9
Processing floor 8
Processing floor 7
Processing floor 6
Processing floor 5
Processing floor 4
Processing floor 3
Processing floor 2
Processing floor 1
Reached floor 0
Example 3: Accumulating Until Threshold
total_area = 0
target_area = 2000
room_count = 0
# Average room size
room_size = 420
print(f"Adding rooms until {target_area}m² is reached:")
while total_area < target_area:
room_count += 1
total_area += room_size
print(f" Room {room_count}: {total_area}m² total")
print(f"\\nNeeded {room_count} rooms to reach {target_area}m²")
Output:
Adding rooms until 2000m² is reached:
Room 1: 420m² total
Room 2: 840m² total
Room 3: 1260m² total
Room 4: 1680m² total
Room 5: 2100m² total
Needed 5 rooms to reach 2000m²
Combining while with Lists
You can use while loops with lists, though for loops are usually clearer.
sheets = ["A-101", "A-102", "A-201", "A-202"]
index = 0
while index < len(sheets):
print(sheets[index])
index += 1
This works, but a for loop is simpler:
sheets = ["A-101", "A-102", "A-201", "A-202"]
for sheet in sheets:
print(sheet)
Use the right tool for the job. If you have a list, use a for loop.
Common Mistakes
Forgetting to update the condition variable
# Infinite loop!
count = 0
while count < 5:
print(count)
# Missing: count += 1
Always update the variable that affects the condition.
Wrong comparison operator
floor = 5
# This never runs (condition is immediately false)
while floor < 0:
print(floor)
floor -= 1
If floor starts at 5, it's never less than 0. The loop never executes. You probably meant floor > 0.
No exit condition
# Infinite loop!
approved = False
while not approved:
print("Waiting for approval...")
# approved never changes to True
Make sure there's a way for the condition to become false.
Add a safety limit:
approved = False
checks = 0
max_checks = 10
while not approved and checks < max_checks:
checks += 1
print(f"Check {checks}: Waiting for approval...")
# Simulate approval
if checks == 5:
approved = True
Off-by-one errors
count = 1
# Runs 4 times, not 5
while count < 5:
print(count)
count += 1
# Output: 1, 2, 3, 4 (missing 5)
If you want to include 5, use <=:
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1, 2, 3, 4, 5
When NOT to Use while Loops
Don't use while when for is clearer:
# Awkward
rooms = ["Office 1", "Office 2", "Office 3"]
i = 0
while i < len(rooms):
print(rooms[i])
i += 1
# Better
for room in rooms:
print(room)
Don't use while for fixed iterations:
# Awkward
count = 0
while count < 10:
print(f"Floor {count + 1}")
count += 1
# Better
for floor in range(1, 11):
print(f"Floor {floor}")
Use while only when the number of iterations depends on a changing condition.
Assignment
<div class="lesson-content__panel" markdown="1">
- Create a new file called
while_loops.py - Basic countdown:
- Start at 5
- Loop while count > 0
- Print each number
- Decrement count
- Count up to target:
- Start at 0
- Target: 10
- Loop while count < target
- Print each number
- Increment count
- Floor descent:
- Start at floor 8
- Count down to ground (0)
- Print each floor number
- Accumulate until threshold:
- Start with total = 0
- Target = 1000
- Add 150 each iteration
- Print running total
- Stop when target is reached or exceeded
- Revision counter:
- Start at revision 0
- Max revisions = 5
- Loop while revision < max
- Print revision number
- Increment revision
- Conditional exit:
- Start with status = "Draft"
- Counter = 0
- Loop while status != "Approved" and counter < 10
- Increment counter each time
- Set status = "Approved" when counter reaches 5
- Print final status and counter
- Compare with for loop:
- Write a while loop that counts 1-10
- Write a for loop with range() that does the same
- See which is clearer
- Intentional mistakes:
- Write a while loop that would run infinitely (but comment it out!)
- Write a while loop with wrong comparison (condition never true)
- See what happens with off-by-one errors
</div>
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- <a class="knowledge-check-link" href="#basic-while-loop">What does a while loop do?</a>
- <a class="knowledge-check-link" href="#the-syntax">When does a while loop stop running?</a>
- <a class="knowledge-check-link" href="#updating-the-condition">Why must you update the condition variable?</a>
- <a class="knowledge-check-link" href="#infinite-loops">What causes an infinite loop?</a>
- <a class="knowledge-check-link" href="#while-vs-for">When should you use while instead of for?</a>
- <a class="knowledge-check-link" href="#when-not-to-use-while-loops">When is a for loop better than while?</a>
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's while loop documentation covers the technical details
- Real Python's while loop guide provides additional examples and patterns