Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
8  
Wow, I never even knew about this. – detly Jul 21 '10 at 7:52
1  
@detly: That's because most people avoid this construct. :) I believe Guido mentioned during the Py3k process that, at the very least, the choice of the word else for 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:26
2  
@Nicholas Knight - yeah, tempting though it is, it'd probably be something only I understood on first glance. Any other poor sap would have to go and look at the language spec, or go back in time and post a question here on Sta- heeeeey... – detly Jul 21 '10 at 8:43
4  
The idea behind choosing 'else' is that this construct is supposedly often used in conjunction with an 'if X: break' inside the while loop. Since the 'else' clause is executed if we don't break out of the loop, it forms a kinda-sorta 'else' to the 'if'. – Jonathan Hartley Nov 22 '13 at 10:25
1  
They should rename it after:. – naught101 Mar 14 at 22:42

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()
share|improve this answer
3  
+1: good example of how it affects usage! :-) – eruciform Jul 21 '10 at 2:54
8  
"The else clause is only executed when your while condition becomes false." The wording here implies that your while state goes from a state of true to false and than the else will be executed. However, if the while is never true, the else clause will still be executed. – user597608 Oct 10 '14 at 21:11
    
pseudocode So correct me if I'm wrong, but this is exactly the same as while {} something except that the something will be skipped if you break in the while loop. – Daniel Kaplan Mar 18 '15 at 21:48

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. :-("
share|improve this answer

In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.

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.

for k in [2, 3, 5, 7, 11, 13, 17, 25]:
    for m in range(2, 10):
        if k == m:
            continue
        print 'trying %s %% %s' % (k, m)
        if k % m == 0:
            print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
            break
    else:
        continue
    print 'breaking another level of loop'
    break
else:
    print 'no divisor could be found!'

In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!

share|improve this answer
    
Why the downvote? – Mark Oct 17 '14 at 18:21
1  
I didn't downvote but I think i know why someone did. You're not answering the question and you're providing 14 lines of code with only 2 lines of description. If there is a relevance to the question asked you're not telling us... – BlueEel Dec 1 '14 at 12:01
1  
@BlueEel thanks for the feedback! I've added more explanation about the code, and made it more clear how this answers the question (because it does answer part of it). – Mark Dec 3 '14 at 12:52
    
You managed to put your code in context and though you're not answering all the questions I see the relevance now. I upvoted your answer as it is now useful to newcomers and novices (as myself in regards of python). - Thanks, I learned something. – BlueEel Dec 3 '14 at 23:31
    
I like the simple application -- now I see why someone might use it. Though I've never seen a need for it. – gabe Feb 25 '15 at 10:23

The else-clause is executed when the while-condition evaluates to false.

From the documentation:

The while statement is used for repeated execution as long as an expression is true:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

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 else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

share|improve this answer

My answer will focus on WHEN we can use while/for-else.

At the first glance, it seems there is no different when using

while CONDITION:
    EXPRESSIONS
print 'ELSE'
print 'The next statement'

and

while CONDITION:
    EXPRESSIONS
else:
    print 'ELSE'
print 'The next statement'

Because the print 'ELSE' statement seems always executed in both cases (both when the while loop finished or not run).

Then, it's only different when the statement print 'ELSE' will not be executed. It's when there is a breakinside the code block under while

In [17]: i = 0

In [18]: while i < 5:
    print i
    if i == 2:
        break
    i = i +1
else:
    print 'ELSE'
print 'The next statement'
   ....:
0
1
2
The next statement

If differ to:

In [19]: i = 0

In [20]: while i < 5:
    print i
    if i == 2:
        break
    i = i +1
print 'ELSE'
print 'The next statement'
   ....:
0
1
2
ELSE
The next statement

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 the while clause will not be executed.

share|improve this answer

The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).

So the output would be this:

5
4
3
2
1
what the...
share|improve this answer
    
I know but this kind of while/else doesn't work in Java. I find it quite interesting when I figured out it works in Python. I was just curious and wanted to know the technical reason. – Ivan Jul 21 '10 at 2:57
4  
@Ivan: It's not so much that it doesn't work in Java but that it doesn't exist in Java. It could be made to work, if someone cared to add it to the language. – Ignacio Vazquez-Abrams Jul 21 '10 at 7:52

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...

n = 5
while n != 0:
    print n
    n -= 1
print "what the..."
share|improve this answer
5  
No, the difference is that the else block will not be executed if you are leaving loop using break or return keyword. In your example, print will be executed also if loop has ended on break command. – Mariusz Pluciński Oct 21 '13 at 16:43
    
You describe how most people wish that the feature worked, not how it actually works! – dotancohen Feb 29 at 9:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.