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.
Example 1: While Else
In this example, we will write else block for while loop statement.
i = 0 while i < 5: print(i) i += 1 else: print('Printing task is done.')
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.
f = open("sample.txt", "r") while True: line = f.readline() if not line: break print(line.strip()) else: f.close
Hi User! Welcome to Python Examples. Continue Exploring.
In this tutorial of Python Examples, we learned what while else is, its syntax, and how to use it in Python programming using examples.