I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
n = 5 while n != 0: print n n -= 1 else: print "what the..."
While loop with else Same as with for loops, while loops can also have an optional else block. The else part is executed if the condition in the while loop evaluates to False . The while loop can be terminated with a break statement.
What is For Else and While Else in Python? For-else and while-else are useful features provided by Python. In simple words, you can use the else block just after the for and while loop. Else block will be executed only if the loop isn't terminated by a break statement.
This lesson covers the while-loop-else -clause, which is unique to Python. The else -block is only executed if the while -loop is exhausted.
The else
clause is only executed when your while
condition becomes false. If you break
out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
if condition: handle_true() else: handle_false()
is analogous to the looping construct:
while condition: handle_true() else: # condition is false now, handle and go on with the rest of the program handle_false()
An example might be along the lines of:
while value < threshold: if not process_acceptable_value(value): # something went wrong, exit the loop; don't pass go, don't collect 200 break value = update(value) else: # value >= threshold; pass go, collect 200 handle_threshold_reached()
The else
clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break
or return
out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values: if value == 5: print "Found it!" break else: print "Nowhere to be found. :-("
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