The while loop in Python repeatedly executes a block of statements as long as a test expression evaluates to True.
Indefinite vs. Definite Iteration: Unlike the sequence-driven for loop, a while loop excels when the exact iteration count is unknown in advance (such as reading user input() or streaming records). Combine with conditional if-else branches, loop controls (break and continue), and the unique while...else construct to build robust workflows.
The while loop evaluates its test condition before each cycle:
# Formal syntax of Python while loop
while condition:
statement_1
statement_2
update_expression
else:
# Optional block executed when condition naturally turns False
else_statement
| Component | Requirement | Operational Rule & Execution Behavior |
|---|---|---|
condition |
Mandatory | Any expression evaluated in a boolean context using bool(). Loops while truthy. |
Loop Body |
Mandatory | Indented block containing statements. Must progress state to avoid infinite loops. |
else: |
Optional | Executes immediately after condition evaluates to False. Skipped on break. |
Unlike for loops which automatically iterate over a collection, a while loop requires explicitly incrementing the counter variable (such as i = i + 1). Statements inside the block must be indented with consistent indentation:
# 1. Basic while loop with counter increment
i = 0
while i < 5:
print(i)
i = i + 1Terminal Output:
0
1
2
3
4
Python allows attaching an optional else block directly to while loops. It runs only when the loop condition naturally becomes False:
# 2. while loop with else clause
i = 0
while i < 5:
print(i)
i = i + 1
else:
print("i am outside the loop")Terminal Output:
0
1
2
3
4
i am outside the loop
Python provides two control statements to alter execution flow:
break: Immediately terminates the loop, jumping past the construct (bypassing any else block).continue: Skips the remainder of the current iteration and jumps directly back to the condition evaluation.
# 3. Skipping iterations with continue
i = 0
while i < 5:
i = i + 1
if i == 3:
continue # Skips printing 3 and returns to condition
print(i)
else:
print("i am outside the loop")Terminal Output:
1
2
4
5
i am outside the loop# 4. Terminating loops early with break
i = 0
while i < 5:
i = i + 1
if i == 3:
break # Immediately exits loop; else block is skipped!
print(i)
else:
print("i am outside the loop")Terminal Output:
1
2
When nesting while loops, ensure the inner counter variable is reset before each outer cycle:
# 5. Nested while loop (2D grid generation)
i = 0
while i < 5:
j = 0
while j < 5:
print("*", end="")
j = j + 1
print("")
i = i + 1Terminal Output:
*****
*****
*****
*****
*****
Prime number testing highlights the synergy between while, break, and else:
# 6. Prime number check using while...else
num = 29
i = 2
while i <= num // 2:
if num % i == 0:
print(num, "is not a prime number")
break
i = i + 1
else:
print(num, "is a prime number")Terminal Output:
29 is a prime numberGenerating all prime numbers within a range using nested while loops:
# 7. Displaying all prime numbers up to 100
limit = 100
candidate = 2
while candidate <= limit:
divisor = 2
while divisor <= candidate // 2:
if candidate % divisor == 0:
break
divisor = divisor + 1
else:
print(candidate, end=" ")
candidate = candidate + 1
print("")Terminal Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Accumulating user inputs until a sentinel value is reached:
# 8. Accumulating user inputs until sentinel zero
my_sum = 0
user_input = ""
# Emulated test values: 10, 25, 15, 0
test_inputs = iter(["10", "25", "15", "0"])
while user_input != "0":
user_input = next(test_inputs)
my_sum = my_sum + int(user_input)
else:
print("Exited loop. The sum:", my_sum)Terminal Output:
Exited loop. The sum: 50Emulating do-while loops where code executes at least once before checking the exit condition:
# 9. Emulating do-while loops in Python
counter = 0
while True:
print("Executed step:", counter)
counter = counter + 1
if counter >= 3:
break # Exit condition verified at bottomTerminal Output:
Executed step: 0
Executed step: 1
Executed step: 2
Practice indefinite iteration, sentinel loops, and nested patterns in our companion Jupyter Notebook:
Explore interactive code cells, benchmark while vs for loops, test prime generation algorithms, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify while loop mechanics:
# 10. Self-verifying unit test suite for while loop mechanics
# Test 1: Iterations count
count, n = 0, 0
while n < 10:
count, n = count + 1, n + 1
assert count == 10 and n == 10
# Test 2: while-else execution without break
ran_else, k = False, 0
while k < 3:
k = k + 1
else:
ran_else = True
assert ran_else is True
# Test 3: while-else skipped when break triggers
broke, ran_break_else, m = False, False, 0
while m < 10:
if m == 2:
broke = True
break
m = m + 1
else:
ran_break_else = True
assert broke is True and ran_break_else is False
print("All while loop unit assertions successfully verified!")Terminal Output:
All while loop unit assertions successfully verified!
Use for when iterating over a known sequence or collection. Use while when looping depends on an external condition, user input, or unknown stopping point.
No. The else block runs only if the loop terminates naturally when the condition becomes False. Triggering break skips the else block.
Python has no native do-while keyword. Use an infinite loop while True: with an if condition: break placed at the end of the body.
Include a guaranteed exit condition with break or pass a maximum iteration counter guard.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.