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..."
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..."
The
else
clause is only executed when yourwhile
condition becomes false. If youbreak
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:
is analogous to the looping construct:
An example might be along the lines of:
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
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 youbreak
orreturn
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:
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...
The
else:
statement is executed when and only when the while loop no longer meets its condition (in your example, whenn != 0
is false).So the output would be this:
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
print 'ELSE'
statement seems always executed in both cases (both when thewhile
loop finished or not run).Then, it's only different when the statement
print 'ELSE'
will not be executed. It's when there is abreak
inside the code block underwhile
If differ to:
return
is not in this category, because it does the same effect for two above cases.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
else
clause or right after thewhile
clause will not be executed.