我注意到下面的代码在Python中是合法的。我的问题是为什么?有什么特别的原因吗?

n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."

许多初学者在尝试在while或for循环中放入if/else块时无意中发现了这种语法,并且没有正确地缩进else。解决方案是确保else块与if块对齐,假设您打算对它们进行配对。这个问题解释了为什么它没有导致语法错误,以及产生的代码意味着什么。我还得到了一个IndentationError。我该怎么解决呢?,用于报告语法错误的情况。


当前回答

else子句在正常退出一个块时执行,比如击中循环条件或从try块底部掉下去。如果您中断或返回一个块,或引发异常,则不会执行。它不仅适用于while和for循环,还适用于try块。

您通常会在通常会提前退出循环的地方发现它,并且在意想不到/不寻常的情况下运行到循环的末尾。例如,如果你在一个列表中循环寻找一个值:

for value in values:
    if value == 5:
        print "Found it!"
        break
else:
    print "Nowhere to be found. :-("

其他回答

else子句在正常退出一个块时执行,比如击中循环条件或从try块底部掉下去。如果您中断或返回一个块,或引发异常,则不会执行。它不仅适用于while和for循环,还适用于try块。

您通常会在通常会提前退出循环的地方发现它,并且在意想不到/不寻常的情况下运行到循环的末尾。例如,如果你在一个列表中循环寻找一个值:

for value in values:
    if value == 5:
        print "Found it!"
        break
else:
    print "Nowhere to be found. :-("

else:语句当且仅当while循环不再满足它的条件时执行(在您的示例中,当n != 0为假时)。

所以输出是这样的:

5
4
3
2
1
what the...

As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.

我知道这是个老问题,但是…

正如Raymond Hettinger所说,应该调用while/no_break而不是while/else。 如果你看一下这个片段,我发现它很容易理解。

n = 5
while n > 0:
    print n
    n -= 1
    if n == 2:
        break
if n == 0:
    print n

现在,我们不用在while循环后检查condition,而是用else替换它,然后去掉那个检查。

n = 5
while n > 0:
    print n
    n -= 1
    if n == 2:
        break
else:  # read it as "no_break"
    print n

我总是把它读成while/no_break来理解代码,这种语法对我来说更有意义。

当while-condition的值为false时,else子句将被执行。

从文档中可以看到:

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.