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:

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:

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: