Sometimes, not very often, you will see a loop in python like below:
# do something
# do something else
At first glance, you may think it’s a typo, shouldn’t it be
Well, it is something legit in python, and has the following statement:
whilestatement is used for repeated execution as long as an expression is true.
while_stmt ::= “while”
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.
breakstatement executed in the first suite terminates the loop without executing the
continuestatement executed in the first suite skips the rest of the suite and goes back to testing the expression.
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.
print ('do something else')===============vs.while condition:
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
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
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.
except Error as e:
handle when no exception raised.