0
0
Pythonprogramming~5 mins

While–else behavior in Python

Choose your learning style9 modes available
Introduction

The else part after a while loop runs only if the loop finishes normally without being stopped early.

You want to do something after a loop completes all its steps.
You want to check if a loop ended because it ran out of items or because it was stopped.
You want to run special code only if the loop did not break early.
You want to avoid extra flags to track if a loop ended normally.
Syntax
Python
while condition:
    # code to repeat
else:
    # code to run if loop ends normally

The else block runs only if the while loop condition becomes false.

If the loop is stopped by a break, the else block does not run.

Examples
This prints numbers 0 to 2, then prints 'Loop finished' because the loop ended normally.
Python
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print('Loop finished')
This prints 0, then breaks when count is 1, so 'Loop finished' is not printed.
Python
count = 0
while count < 3:
    if count == 1:
        break
    print(count)
    count += 1
else:
    print('Loop finished')
Sample Program

This program counts down from 5 to 1, then prints a message after the loop ends normally.

Python
n = 5
while n > 0:
    print(n)
    n -= 1
else:
    print('Done counting down!')
OutputSuccess
Important Notes

Remember, else after while is not like an if condition; it runs only if no break happens.

You can use while-else to detect if a search loop found what it was looking for or not.

Summary

The else block after a while runs only if the loop ends without break.

Use it to run code after a loop finishes all its cycles.

It helps avoid extra flags to check loop completion.