我不确定 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")`
如果我从列表中删除“垃圾邮件”,现在条件始终为 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")
请您参考如下方法:
对于 Python 中的 for 循环,else block 在循环正常结束时执行,即没有 break 语句。 continue 不会以任何方式影响它。
如果 for 循环因为 break 语句而结束,则 else block 将不会执行。如果循环正常退出(没有 break),那么 else block 将被执行。
来自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 添加到列表中并再次运行它,它将 break 并且 else 将不会打印。在大多数其他语言中,您必须添加一些标记 bool 值,如 found 并在找到 4 时将其设置为 True,然后只打印如果 found 为 False,循环后的语句。
