PythonMastery

while loop with else in Python

A while loop can have an else block. It runs when the condition becomes false, but not when the loop ends with break. A countdown and a password check.

A while loop can have an else block. The else runs once, after the loop condition becomes false. It does not run if the loop ends with break.

The program

python
n = 5

while n > 0:
    print(n)
    n -= 1
else:
    print("Lift off!")
output
5
4
3
2
1
Lift off!

How it works

Where else is useful: three tries

Here the user has three tries to type the password. A correct password ends the loop with break, so the else is skipped. Three wrong answers end the loop normally, so the else runs:

python
tries_left = 3

while tries_left > 0:
    password = input("Password: ")
    if password == "swordfish":
        print("Welcome!")
        break
    tries_left -= 1
    print(f"Wrong password. Tries left: {tries_left}")
else:
    print("Too many wrong tries. Account locked.")

Typed in this example: fishsword, Swordfish, sword fish. Press Run to type your own.

output
Password: fishsword
Wrong password. Tries left: 2
Password: Swordfish
Wrong password. Tries left: 1
Password: sword fish
Wrong password. Tries left: 0
Too many wrong tries. Account locked.

Without else, you would need an extra variable such as logged_in = False to know, after the loop, why it stopped. (A real program would never store a password in its code like this. It is here only to show the loop.)

Related programs: for else.

Learn the idea: Loops: for, while, and the Pythonic Patterns