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

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

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


当前回答

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

其他回答

假设要在单链表中搜索元素x

    def search(self, x):
        position = 1
        p =self.start
        while p is not None:
            if p.info == x:
                print(x, " is at position ", position)
                return True
            position += 1
            p = p.link
        else:
            print(x, "not found in list") 
            return False

因此,如果条件失败,其他将执行,希望它有助于!

请允许我举例说明为什么要使用else子句。但是:

我的观点在Leo的回答中得到了更好的解释 我使用for-而不是while-循环,但else工作类似(除非遇到break,否则执行) 有更好的方法可以做到这一点(例如,将其包装到函数中或引发异常)

打破多级循环

它是这样工作的:外部循环在结尾有一个break,所以它只会执行一次。但是,如果内部循环完成(没有找到除数),那么它将到达else语句,并且永远不会到达外部断点。这样,内部循环中的中断将跳出两个循环,而不仅仅是一个循环。

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!'

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

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

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

else子句只在while条件变为false时执行。如果跳出循环,或者引发异常,则不会执行该循环。

一种考虑它的方法是作为一个关于条件的if/else结构:

if condition:
    handle_true()
else:
    handle_false()

类似于循环结构:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

一个例子可能是:

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()

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