Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else clause on Python while statement

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..." 
like image 788
Ivan Avatar asked Jul 21 '10 02:07

Ivan


People also ask

Can you put an else in a while statement?

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 Python?

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.

Can else :' block be use with while loops?

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.


2 Answers

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() 
like image 164
ars Avatar answered Sep 28 '22 22:09

ars


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. :-(" 
like image 45
John Kugelman Avatar answered Sep 28 '22 23:09

John Kugelman