Loops with while
Concepts covered: Conditional Loops
A while loop repeats as long as its condition is True. Unlike a for loop, which runs a fixed number of times, a while loop keeps going until the condition becomes False, so it fits cases where you don't know in advance how many iterations you need.
Basic while syntax
A while loop has the form: while condition: followed by an indented block. The condition is checked before each iteration:
count = 0
while count < 5:
print("Count is", count)
count = count + 1
print("Loop finished!")Count is 0 Count is 1 Count is 2 Count is 3 Count is 4 Loop finished!
The loop checks the condition, executes the body if True, then checks again. When count reaches 5, the condition becomes False and the loop ends. Here is the execution model step by step:
- Evaluate condition: Python checks whether the while condition is True or False
- Run loop body: If True, execute all indented statements inside the loop
- Update state: The loop body should change something that affects the condition
- Repeat or exit: Jump back to step 1. If condition is False, skip to code after the loop
Comparing while and for
The choice mostly comes down to whether you know the number of iterations up front:
- Use for when
- Iterating over a sequence
- You know how many times to loop
- Processing each item in a collection
- Using range() for a count
- Use while when
- Unknown number of iterations
- Waiting for a condition
- User input loops
- Reading until end of data
Most loops you write in real code fall into one of the cases below.
Picking a loop type
- Processing every item in a list, string, or file: use a for loop.
- Repeating an action a known number of times: use for with range().
- Waiting for user input or an external condition: use a while loop.
- Polling or retrying until success or timeout: use while with a counter.
Common while patterns
While loops usually show up in a handful of shapes:
# Countdown
n = 3
while n > 0:
print(n)
n = n - 1
print("Liftoff!")
print("---")
# Find first match
items = ["a", "b", "c", "target", "d"]
i = 0
while i < len(items) and items[i] != "target":
i = i + 1
print("Found at index:", i)
print("---")
# Process until empty
queue = [1, 2, 3]
while queue:
item = queue.pop(0)
print("Processing:", item)
print("Queue empty")3 2 1 Liftoff! --- Found at index: 3 --- Processing: 1 Processing: 2 Processing: 3 Queue empty
Avoiding infinite loops
A while loop that never ends is called an infinite loop. It happens when the condition never becomes False, so something in the loop body has to move the condition toward False:
# CORRECT: count increases, eventually >= 3
count = 0
while count < 3:
print(count)
count = count + 1
# WOULD BE WRONG (don't run this!):
# while True: # Never ends!
# print("Forever...")
# WOULD BE WRONG:
# x = 0
# while x < 10:
# print(x)
# # Forgot to increment x!Output:
0 1 2
This while loop has a bug that makes it run forever. Remove the tile that causes it:
Intentional infinite loops with while True
Combining while True with break gives you a loop that exits on complex conditions. It helps most when the exit check belongs in the middle of the loop body rather than at the beginning:
# Simulate reading until valid input
attempts = 0
max_attempts = 3
valid_inputs = ["yes", "no"]
test_inputs = ["maybe", "perhaps", "yes"]
result = None
while True:
if attempts >= max_attempts:
print("Max attempts reached")
break
# Simulate getting input
user_input = test_inputs[attempts]
print("Attempt", attempts + 1, "- Got:", user_input)
attempts += 1
if user_input in valid_inputs:
result = user_input
print("Valid input received!")
break
print("Final result:", result)Output:
Attempt 1 - Got: maybe Attempt 2 - Got: perhaps Attempt 3 - Got: yes Valid input received! Final result: yes
Simulating do-while loops
Python has no do-while loop, the kind that runs the body before it checks the condition. A while True loop with a break inside gets you the same behavior:
count = 5
# This regular while would never run
# while count < 5:
# print("Regular while:", count)
# Simulated do-while runs at least once
count = 5
while True:
print("Do-while style:", count)
count += 1
if count >= 7:
break
print("Done!")Output:
Do-while style: 5 Do-while style: 6 Done!
This pattern guarantees the loop body runs at least once because the condition check happens after the body executes, not before.
About this lesson
This section is part of the Loops: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.