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
else:
# 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:

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
else:
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:
print(i)
if i == 2:
break
i -= 1
else:
print('no break')
print(i)
=========
4
3
no break
2

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):
break
value = update_val_towards_threshold(value)
else:
handle_threshold_reached()

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

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

That’s it!

Happy Reading!