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

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子句,了解语法含义的具体问题。


当前回答

else子句在循环正常完成后执行。这意味着The:==> 只有当循环没有被break语句终止时,才会在for/while语句之后执行else块

for item in lista:
if(obj == item ):
    print("if True then break will run and else not run")
    break;
else:
print("in  else => obj not fount ")

其他回答

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

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

Break关键字用于结束循环。如果I = 9,循环将结束。而任何一个如果条件没有太多的满足,那么其余的部分将由其他条件来完成。

我只是想让自己重新理解一下。我发现下面的方法很有用!

•将else看作是与循环中的if配对(而不是与for配对)-如果条件满足,则打破循环,否则执行此操作-除非它是与多个if配对的else ! •如果所有的“如果”都不满足,那么就做“其他”。 •多个如果实际上也可以被认为是if-elifs!

else语句块中的代码将在for循环未被打破时执行。

for x in xrange(1,5):
    if x == 5:
        print 'find 5'
        break
else:
    print 'can not find 5!'
#can not find 5!

来自文档:break和continue语句,以及循环中的else子句

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers: >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 (Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.) When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions. The continue statement, also borrowed from C, continues with the next iteration of the loop: >>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found a number", num) Found an even number 2 Found a number 3 Found an even number 4 Found a number 5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9

我认为结构是for(if) A else B,而for(if)-else是一个特殊的if-else。这可能有助于了解其他方面。

A和B最多执行一次,这与if-else结构相同。

For (if)可以被认为是一个特殊的if,它会执行一个循环来尝试满足if条件。一旦满足if条件,A和break;别的,B。

我是这样读的:

如果还在运行循环的条件下,做点别的,否则做点别的。