Python While Else Loop: The Complete Guide
In Python, the while statement may have an optional else clause. While loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. After the while loop, we can put the else statement, which will execute if the while condition becomes false. Let’s see while else in detail.
Python While Else
In a while-else loop in Python, With the else statement, we can run a block of code once when the condition no longer is true. A while loop repeatedly executes a target statement as long as a given condition is true.
Syntax of while else
while condition statement(s) else statement(s)
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 else clause is only executed when your while condition becomes false. What I mean by this is that your while state goes from a state of true to false, and then the else will be executed.
However, if the while is never true, the else clause will still be executed. And simple syntax of the while loop is the following.
The else clause is executed if you exit a block normally by hitting the loop condition or falling off the bottom of a try block.
It is not executed if you break or return out of a block or raise an exception. It works for not only a while and for loops but also try blocks.
Syntax of while loop
while expression: statement(s)
Here, the statement(s) may be a single statement or a block of statements.
Implementation of while else statement
Let’s take the example of while else statement.
data = 11 while data < 19: print(data) data += 1 else: print("data is no longer less than 19")
11 12 13 14 15 16 17 18 data is no longer less than 19
You can see from the output that the else-clause is executed when the while-condition evaluates to false. The while statement is used for repeated execution as long as an expression is true.
If initially, the condition is false, so else-clause is executed.
data = 1921 while data < 19: print(data) data += 1 else: print("data is no longer less than 19")
data is no longer less than 19
In this example, data is not less than 19, so it directly executes the else statement.
That’s it for Python while else statement.