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?
else will not execute if there is a break statement in the loop. From the docs:
The
whilestatement 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
elseclause, if present, is executed and the loop terminates.A
breakstatement executed in the first suite terminates the loop without executing theelseclause’s suite. Acontinuestatement 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:
elsesuites always execute when a condition has been evaluated toFalse
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With