← Back to Blog

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!

  • else runs when the condition becomes False naturally
  • else is skipped when break interrupts the loop
  • Same rule as for...else — the keyword is the same, the logic is the same
  • If the loop never runs — else still 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...elseelse runs when the loop completes normally
  • If break interrupts — else is skipped
  • If the loop never runs — else still runs
  • Use it to distinguish between "completed" and "interrupted"
[ login to bookmark ] // copied! 21 views · 1 min
// resources
Code Example while_else.py
← prev Roll until you win next → WHILE Mini Project — Accumulator
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.