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

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

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


当前回答

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:

其他回答

假设要在单链表中搜索元素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

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

在Python中,'while: else:'结构的更好用法应该是,如果'while'中没有执行循环,则执行'else'语句。今天它的工作方式没有意义,因为您可以使用下面的代码获得相同的结果……

n = 5
while n != 0:
    print n
    n -= 1
print "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.

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

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

正如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来理解代码,这种语法对我来说更有意义。