我理解这种结构是如何运作的:

for i in range(10):
    print(i)

    if i == 9:
        print("Too big - I'm giving up!")
        break
else:
    print("Completed successfully")

但我不明白为什么在这里使用else作为关键字,因为它表明有问题的代码只在for块未完成时运行,这与它所做的相反!无论我怎么想,我的大脑都不能从for语句无缝地过渡到else语句块。对我来说,continue和continuouswith更有意义(我正试着训练自己这样读它)。

我想知道Python程序员是如何在头脑中(或者大声地,如果你喜欢)阅读这个结构的。也许我遗漏了一些可以使这些代码块更容易破译的东西?


这个问题是关于底层设计决策的,也就是说,为什么能够编写这些代码是有用的。另请参阅Python while语句中的Else子句,了解语法含义的具体问题。


当前回答

The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.

for a in range(3):
    print(a)
    if a==4: # change value to force break or not
        break
else: #no break  +10 for whoever thought of this decoration
    print('for completed OK')

print('statement after for loop')

编辑-我注意到这个问题仍然在运行

第二个更好的想法……

“没有休息”的评论是负面的。要理解一个正的断言要容易得多,那就是for可迭代对象已经用完了。

for a in range(3):
    print(a)
    if a==4: # change value to force break or not
        print('ending for loop with a break')
        break
else: # for iterable exhausted  
    print('ending for loop as iterable exhausted')

print('for loop ended one way or another')

这也强化了这种解释

if iterable_supplies_a_value:
    run_the_for_with_that_value
else:
    do_something_else

其他回答

The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.

for a in range(3):
    print(a)
    if a==4: # change value to force break or not
        break
else: #no break  +10 for whoever thought of this decoration
    print('for completed OK')

print('statement after for loop')

编辑-我注意到这个问题仍然在运行

第二个更好的想法……

“没有休息”的评论是负面的。要理解一个正的断言要容易得多,那就是for可迭代对象已经用完了。

for a in range(3):
    print(a)
    if a==4: # change value to force break or not
        print('ending for loop with a break')
        break
else: # for iterable exhausted  
    print('ending for loop as iterable exhausted')

print('for loop ended one way or another')

这也强化了这种解释

if iterable_supplies_a_value:
    run_the_for_with_that_value
else:
    do_something_else

简单来说,你可以这样想;

如果它在for循环中遇到break命令,else部分将不会被调用。 如果在for循环中没有遇到break命令,则调用else部分。

换句话说,如果for循环迭代没有被break“打断”,else部分将被调用。

下面是一种我从未见过其他人提到过的思考方法:

首先,请记住for循环基本上只是while循环的语法糖。例如,循环

for item in sequence:
    do_something(item)

可以重写(大约)为

item = None
while sequence.hasnext():
    item = sequence.next()
    do_something(item)

其次,记住while循环基本上只是重复if块!你总是可以把while循环读成“如果这个条件为真,执行body,然后回来再次检查”。

因此while/else非常有意义:它与if/else结构完全相同,只是增加了循环直到条件变为false的功能,而不是只检查一次条件。

然后for/else也非常有意义:因为所有的for循环都只是while-循环之上的语法糖,你只需要弄清楚底层while-循环的隐式条件是什么,然后else对应于当条件变为False时。

我认为文档对else有很好的解释,继续

[…当循环因列表耗尽而终止(使用for)或当条件变为false(使用while)时执行,但当循环由break语句终止时不执行。”

来源:Python 2文档:控制流教程

我同意,它更像是一个'elif not[条件(s)提高中断]'。

我知道这是一个老话题,但我现在正在研究同样的问题,我不确定是否有人能以我理解的方式抓住这个问题的答案。

对我来说,有三种方法来“阅读”For…else or While…所有等价的Else语句是:

Else ==如果循环正常完成(没有中断或错误) Else ==如果循环没有遇到断点 Else == Else not(条件引发中断)(假设存在这样的条件,否则就不会有循环)

因此,从本质上讲,循环中的“else”实际上是一个“elif…”,其中'…’表示(1)不中断,相当于(2)NOT[条件(s)引发中断]。

我认为关键在于,如果没有break, else是没有意义的,所以for…其他的包括:

for:
    do stuff
    conditional break # implied by else
else not break:
    do more stuff

a的基本元素。else循环如下所示,你可以用更简单的英语阅读它们:

for:
    do stuff
    condition:
        break
else: # read as "else not break" or "else not condition"
    do more stuff

正如其他帖子所说,当你能够找到你的循环正在寻找的东西时,通常会引发一个break,所以else:变成了“如果目标物品没有找到,该怎么办”。

例子

您还可以同时使用异常处理、中断和for循环。

for x in range(0,3):
    print("x: {}".format(x))
    if x == 2:
        try:
            raise AssertionError("ASSERTION ERROR: x is {}".format(x))
        except:
            print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
            break
else:
    print("X loop complete without error")

结果

x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run

例子

一个简单的例子,断点被击中。

for y in range(0,3):
    print("y: {}".format(y))
    if y == 2: # will be executed
        print("BREAK: y is {}\n----------".format(y))
        break
else: # not executed because break is hit
    print("y_loop completed without break----------\n")

结果

y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run

例子

没有中断的简单示例,没有引发中断的条件,也没有遇到错误。

for z in range(0,3):
     print("z: {}".format(z))
     if z == 4: # will not be executed
         print("BREAK: z is {}\n".format(y))
         break
     if z == 4: # will not be executed
         raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
     print("z_loop complete without break or error\n----------\n")

结果

z: 0
z: 1
z: 2
z_loop complete without break or error
----------