继续声明中的其他部分如何工作?

How else part work in continue statement?

我不确定 continue 语句在带有 else 子句的 for 循环中时是如何解释的。

如果条件为真,break 将从for 循环中退出并且else 部分将不会被执行。如果条件为 False,则 else 部分将被执行。

但是,continue 语句呢?我测试了好像是continue语句执行到后,else部分会被执行。这是真的??这是一个代码示例:

# when condition found and it's `true` then `else` part is executing :

edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        continue
    print("Great, delicious " + food)

else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")`

如果我从列表中删除 "spam",现在条件总是 false 并且从未找到,但仍然执行 else 部分:

edibles = ["ham","eggs","nuts"]
for food in edibles:
    if food == "spam":
        print("No more spam please!")
        continue
    print("Great, delicious " + food)

else:
    print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

您的 else 部分将在两种情况下执行。 else 部分在条件不满足时循环终止时执行 found.Which 是您的代码中发生的事情。但它也可以在没有 continue 语句的情况下工作。

现在break语句的else部分呢,Break语句的else部分只有在以下情况下才会执行:

  • 如果循环正常完成而没有任何中断。
  • 如果循环没有遇到中断。

对于Python中的for循环,当循环正常结束时执行else块,即没有break语句。 continue 不会影响它。

如果for循环因为break语句而结束,那么else块将不会执行。如果循环正常退出(没有break),那么else块将被执行。

来自docs

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.

我一直记得它,因为 Raymond Hettinger describes it。他说应该叫 nobreak 而不是 else。 (这也是一个很好的视频,解释了 for-else 结构的用处)

示例:

numbers = [1,2,3]
for number in numbers:
    if number == 4:
        print("4 was found")
        break
else:
    print("4 was not found")

当你 运行 上面的代码时,由于 4 不在列表中,循环将不会 break 并且 else 子句将被打印。如果您将 4 添加到列表并再次添加 运行,它将 breakelse 将不会打印。在大多数其他语言中,如果找到 4,则必须添加一些标记布尔值,如 found 并使其成为 True,然后仅在循环后打印语句 if foundFalse