while also has a plan B
The problem...
Your while loop ran. The condition eventually became false. But did it finish normally — or did something interrupt it?
You need to know the difference. And right now, you don't have a clean way to tell.
The idea!
Just like for, a while loop can have an else block. Same rule — else runs when the loop completes normally, without being interrupted by break.
while condition:
# loop body
else:
# runs when condition becomes False — not interrupted by break
Your first while...else
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop complete.")
# 0
# 1
# 2
# Loop complete.
Condition became false naturally — else runs.
When else does NOT run
count = 0
while count < 5:
if count == 3:
break
print(count)
count += 1
else:
print("Loop complete.") # never runs
# 0
# 1
# 2
break interrupted the loop — else is skipped.
A real use case — limited attempts
import random
secret = random.randint(1, 5)
attempts = 0
while attempts < 3:
guess = int(input("Guess (1-5): "))
attempts += 1
if guess == secret:
print(f"Correct! Got it in {attempts} attempt(s).")
break
else:
print(f"Out of attempts. The number was {secret}.")
If the user guesses correctly — break fires — else skipped. If the loop exhausts all three attempts — else runs — and reveals the answer.
No extra flag variable. No extra if after the loop. Clean.
Heads up!
elseruns when the condition becomesFalsenaturallyelseis skipped whenbreakinterrupts the loop- Same rule as
for...else— the keyword is the same, the logic is the same - If the loop never runs —
elsestill runs
The mindset shift
Stop thinking: "else means the condition failed."
Start thinking: "else means the loop ran to completion — without interruption."
What you should understand now
while...else—elseruns when the loop completes normally- If
breakinterrupts —elseis skipped - If the loop never runs —
elsestill runs - Use it to distinguish between "completed" and "interrupted"