Python While Else

Python While Else

Python While Else executes else block when the while condition becomes False. Syntax and working is same as that of Python While, but has an additional else block after while block.

Syntax of While Else

The syntax of while-else in Python is

while condition:
    statement(s)
else:
    statement(s)

The flow of execution for a while else statement is illustrated in the following diagram.

Python While Else

Example 1: While Else

In this example, we will write else block for while loop statement.

Python Program

i = 0
while i < 5:
    print(i)
    i += 1
else:
    print('Printing task is done.')

Output

0
1
2
3
4
Printing task is done.

Example 2: While Else with File Reading

In this example, we will use else block after while block to close the file we read line by line in the while block.

Python Program

f = open("sample.txt", "r")
while True:
    line = f.readline()
    if not line:
        break
    print(line.strip())
else:
    f.close

Output

Hi User!
Welcome to Python Examples.
Continue Exploring.

Summary

In this tutorial of Python Examples, we learned what while else is, its syntax, and how to use it in Python programming using examples.

Like what you read! Bookmark this page for quick access and please share this article with your friends and colleagues.