The while Loop in Python
Introduction
The while loop executes a code block as long as a condition is True. It’s useful when we don’t know in advance how many times to repeat.
Basic Syntax
while condition:
# code block
# executes while condition is True
Simple example:
counter = 1
while counter <= 5:
print(counter)
counter += 1 # Important: update the condition!
# Displays: 1 2 3 4 5
Anatomy of a while Loop
# 1. Initialization
i = 0
# 2. Continuation condition
while i < 5:
# 3. Loop body
print(i)
# 4. Update (avoid infinite loop!)
i += 1
Infinite Loops
An infinite loop occurs when the condition never becomes False:
# WRONG - infinite loop!
i = 0
while i < 5:
print(i)
# Missing: i += 1
# CORRECT
i = 0
while i < 5:
print(i)
i += 1
Intentional infinite loop:
while True:
command = input("Command: ")
if command == "exit":
break # Exits the loop
print(f"You wrote: {command}")
The break Statement
break immediately exits the loop:
i = 0
while i < 10:
if i == 5:
break # Exits when i == 5
print(i)
i += 1
# Displays: 0 1 2 3 4
Searching for an element:
numbers = [3, 7, 2, 9, 5]
target = 9
found = False
i = 0
while i < len(numbers):
if numbers[i] == target:
found = True
break
i += 1
print(f"Found: {found}") # Found: True
The continue Statement
continue skips to the next iteration:
i = 0
while i < 5:
i += 1
if i == 3:
continue # Skips print when i == 3
print(i)
# Displays: 1 2 4 5 (without 3)
Filtering numbers:
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue # Skips even numbers
print(i)
# Displays: 1 3 5 7 9
The else Clause with while
The else block executes when condition becomes False (not on break):
i = 0
while i < 3:
print(i)
i += 1
else:
print("Loop completed normally")
# Displays: 0 1 2 Loop completed normally
With break:
i = 0
while i < 5:
if i == 3:
break
print(i)
i += 1
else:
print("This message won't appear") # Doesn't execute!
# Displays: 0 1 2
Practical application - search:
numbers = [1, 3, 5, 7, 9]
target = 4
i = 0
while i < len(numbers):
if numbers[i] == target:
print(f"Found at index {i}")
break
i += 1
else:
print("Not found") # Displays
# Displays: Not found
Common Patterns
Reading until special value:
total = 0
while True:
number = int(input("Number (0 = stop): "))
if number == 0:
break
total += number
print(f"Total: {total}")
Input validation:
while True:
age = input("Age (1-120): ")
if age.isdigit():
age = int(age)
if 1 <= age <= 120:
break
print("Invalid age!")
print(f"Age: {age}")
Countdown:
n = 5
while n > 0:
print(n)
n -= 1
print("Start!")
# 5 4 3 2 1 Start!
while vs for Comparison
| Criterion | while | for |
|---|---|---|
| Iteration count | Unknown | Known |
| Condition | Any expression | Sequence iteration |
| Infinite risk | Yes | No |
| Use case | User input | Collection traversal |
# for - when you know iteration count
for i in range(5):
print(i)
# while - when you don't know iteration count
answer = ""
while answer != "yes":
answer = input("Continue? ")
Common Mistakes
1. Accidental infinite loop
i = 0
while i < 5:
print(i)
# Missing: i += 1
2. Wrong condition
i = 10
while i > 5: # Never False if i increases
print(i)
i += 1 # Should be i -= 1
3. Off-by-one errors
# Want 5 iterations but get 4
i = 1
while i < 5: # 1,2,3,4 (4 iterations)
print(i)
i += 1
# Correct for 5 iterations
i = 1
while i <= 5: # 1,2,3,4,5 (5 iterations)
print(i)
i += 1
Key Points for Exam
whilerepeats as long as condition isTruebreakexits the loop immediatelycontinueskips to next iterationelsewith while only executes if nobreak- Ensure condition becomes
Falseat some point - Use
while True+breakfor conditionally exited loops
Review Questions
- When does the
elseblock execute in a while loop? - What’s the difference between
breakandcontinue? - How do you avoid an infinite loop?
- When do you use
whileinstead offor?