Python Control Flow with While…Else…

Photo by Christine Trant on Unsplash

Sometimes, not very often, you will see a loop in python like below:

while condition:
# do something
# do something else

At first glance, you may think it’s a typo, shouldn’t it be if...else... instead?

Well, it is something legit in python, and has the following statement:

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

while_stmt ::= “while” expression ":" suite
["else" ":"

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.

So the else clause is only executed when your while condition becomes false. If you break out of the loop, use return, or if an exception is raised, it won't be executed.

So why it is needed alongside the popular if...else... ? The truth is, it is actually not used so often, but occasionally, it makes the expression more succinct.

For example, both following statement will have the same results.

while condition:
do something
print ('do something else')
===============vs.while condition:
do something
print ('do something else')
============== both produce:
do something else

However, when there is a break clause, things become a bit different.

i = 4while i > 0:
if i == 2:
i -= 1
print('no break')
no break

You can see the while loop breaks out when i==2 and goes to the else statement. You can construct the above scenario like below:

while value < threshold:
do something wild
if threshold_is_reached(value):
value = update_val_towards_threshold(value)

Note that it works for not only while but also for for loops and try blocks , which might be more familiar to you.

do something
except Error as e:
handle error
handle when no exception raised.

That’s it!

Happy Reading!