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..."
Thanks.
|
I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
Thanks. |
||||
|
The One way to think about it is as an if/else construct with respect to the condition:
is analogous to the looping construct:
An example might be along the lines of:
|
|||||||||||||
|
|
The 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:
|
||||
|
|
|
In reply to Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works! |
|||||||||||||||||||||
|
|
The else-clause is executed when the while-condition evaluates to false. From the documentation:
|
||||
|
|
|
My answer will focus on WHEN we can use while/for-else. At the first glance, it seems there is no different when using
and
Because the Then, it's only different when the statement
If differ to:
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in |
|||
|
|
|
The So the output would be this:
|
|||||||||
|
|
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
|
|||||||||
|
elsefor this use had been a remarkably bad idea, and that they wouldn't be doing any more of these. – Nicholas Knight Jul 21 '10 at 8:26after:. – naught101 Mar 14 at 22:42