Summary: in this tutorial, you’ll learn about the Python while else statement and how to use it effectively.
Introduction to Python while else statement #
In Python, the while statement may have an optional else clause:
while condition:
# code block to run
else:
# else clause code blockCode language: PHP (php)In this syntax, the condition is checked at the beginning of each iteration. The code block inside the while statement will execute as long as the condition is True.
When the condition becomes False and the loop runs normally, the else clause will execute. However, if the loop is terminated prematurely by either a break or return statement, the else clause won’t execute at all.
The following flowchart illustrates the while...else clause: