continue语句中的其他部分如何工作?

2024-07-03 06:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: noinforiffood语句spam条件
2条回答

您的else部分将在这两种情况下执行。 else当条件不满足时循环终止时执行的部分找到了。哪个是代码中发生的事情。但是它也可以在没有continue语句的情况下工作。你知道吗

那么break语句的else部分呢,break语句的else部分将仅在以下情况下执行:

  • 如果循环正常完成,没有任何中断。你知道吗
  • 如果循环没有遇到中断。你知道吗

enter image description here

对于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.

我总是记得这件事,因为雷蒙德·赫廷格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不在列表中,因此循环将不会breakelse子句将打印出来。如果您将4添加到列表中并再次运行,它将breakelse将不会打印。在大多数其他语言中,您必须添加一些sentinel boolean,如found,并使其成为True如果您找到一个4,那么如果foundFalse,则只打印循环后面的语句。你知道吗

相关问题 更多 >