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:
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 theelse
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
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!