Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit(s) of having 'else clause' for the while loop in python?

Any code after while loop will execute when the condition in the while loop becomes False. It is the same for the code in the 'else clause' section of while loop in python. So What's the advantage of having 'else' in the while loop?

like image 224
Kamran Bigdely Avatar asked Feb 26 '23 12:02

Kamran Bigdely


1 Answers

else will not execute if there is a break statement in the loop. From the docs:

The while statement is used for repeated execution as long as an expression is true:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

(emphasis mine) This also works for forloops, by the way. It's not often useful, but usually very elegant when it is.


I believe the standard use case is when you are searching through a container to find a value:

for element in container:
    if cond(element):
        break
else:
    # no such element

Notice also that after the loop, element will be defined in the global scope, which is convenient.


I found it counterintuitive until I heard a good explanation from some mailing list:

else suites always execute when a condition has been evaluated to False

So if the condition of a while loop is executed and found false, the loop will stop and the else suite will run. break is different because it exits the loop without testing the condition.

like image 187
Katriel Avatar answered Feb 28 '23 01:02

Katriel