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

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

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


当前回答

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

所以输出是这样的:

5
4
3
2
1
what the...

其他回答

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

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

thing = 'hay'
while thing:
  if thing == 'needle':
    print('I found it!!')  # wrap up for break
    break
  thing = haystack.next()
else:
  print('I did not find it.')  # wrap up for no-break

可能不幸命名为else-子句的地方是您从循环耗尽中不间断地结束的地方。

你可以没有它,如果

你中断与return或raise→调用或尝试后的整个代码是你的不可中断的地方 你在while之前设置了默认值(例如found = False) 但它可能会隐藏else子句知道要避免的错误

如果您使用带有非平凡结束符的multi-break,那么您应该在break之前使用一个简单的赋值,对no-break使用一个else子句赋值,并使用If -elif-else或match-case来避免重复非平凡的break处理代码。

注:同样适用于thing in haystack:

我的回答将集中在我们什么时候可以使用while/for-else。

乍一看,使用时似乎没有什么不同

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

and

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

因为打印'ELSE'语句似乎总是在这两种情况下执行(当while循环结束或不运行时)。

然后,只有当打印'ELSE'语句不被执行时,情况才有所不同。 它是在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

如与:

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不在此类别中,因为它对上述两种情况具有相同的效果。

异常引发也不会造成差异,因为当它引发时,下一个代码将在异常处理程序中执行(block除外),else子句或while子句后面的代码将不会被执行。

else子句只在while条件为false时执行。

下面是一些例子:

例1:初始条件为false,因此执行else-clause。

i = 99999999

while i < 5:
    print(i)
    i += 1
else:
    print('this')

输出:

this

例2:while-condition i < 5永远不会变成false,因为i == 3打破了循环,所以else-clause没有执行。

i = 0

while i < 5:
    print(i)
    if i == 3:
        break
    i += 1
else:
    print('this')

输出:

0
1
2
3

例3:while-condition i < 5在i为5时变为false,因此执行else-clause。

i = 0

while i < 5:
    print(i)
    i += 1
else:
    print('this')

输出:

0
1
2
3
4
this