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
n = 5 while n > 0: print(n) n -= 1 else: print("Lift off!")
5 4 3 2 1 Lift off!
How it works
- The loop prints 5, 4, 3, 2, 1. Then
nis 0, son > 0is false and the loop ends. - The loop ended because its condition became false, so the
elseblock runs. - In this program the
elsegives the same result as a plainprint()after the loop. Theelseonly makes a difference when the loop contains abreak.
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:
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.
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.