while loop with else in Python
What is while...else in Python? In Python, a while loop can have an else block, which executes after the loop finishes normally — i.e., when the condition becomes False (not when the loop breaks).
So: • ✅ The else part runs if the loop completes all iterations normally
• ❌ The else part does not run if the loop is exited using break
Syntax
while condition:
# loop body
else:
# code that runs when loop ends normally Explanation:
- condition: A boolean expression (True or False).
- The loop runs while the condition is True.
- Once the condition becomes False, the loop stops.
Example: Normal loop completion (else executes). We can add an else block that runs when the loop finishes normally (not via break).
Python
# Initialize counter
count = 1
while count <= 3:
print("Count:", count)
count = count + 1
else:
print("Loop finished successfully!") Output: Count: 1
Count: 2
Count: 3
Loop finished successfully!
Explanation:
- count starts at 1.
- The loop runs while count <= 3.
- After count becomes 4, the condition is False.
- The loop ends normally, so the else block executes.
Example: Using break (else does NOT execute).
Python
count = 1
while count <= 5:
print("Count:", count)
if count == 3:
break # Exit loop early
count = count + 1
else:
print("Loop finished successfully!") Output: Count: 1
Count: 2
Count: 3
Explanation:
- The loop stops when count == 3 due to break.
- Because the loop didn’t finish normally, the else block did not run.