gpt4 book ai didi

python-3.x - 为什么在 python 中允许 for else

转载 作者:行者123 更新时间:2023-12-05 08:53:01 27 4
gpt4 key购买 nike

我不明白为什么在 python 中允许这样做?

>>> for i in []:
... print(i)
... else:
... print('here')
...
here

这不应该有 else 没有 if 语法错误吗? else 也每次都运行(如果 for 已经迭代或没有迭代)所以它没有连接。

>>> for i in 1,2,3:
... print(i)
... else:
... print('here')
...
1
2
3
here

最佳答案

来自 docs

* else 子句在循环正常完成后执行。这意味着循环没有遇到 break 语句。*

因此,如果您正在执行 for 循环但不知道该元素是否会在循环中找到/是否在循环中返回 true,这将很有用。所以你可以添加一个break语句,如果元素找到/为真就退出循环,或者如果没有找到/为真则执行另一个命令。例如在你的循环中:

for i in []:
print(i)
else:
print('here')

输出

here

在这种情况下,在您的 for 循环中找不到 i。但是,您没有在 for 循环之后执行 break 语句。因此,编译器然后转到 else 语句执行那里的行,因为 for 循环没有中断。

在第二个例子中你有:

for i in 1,2,3:
print(i)
else:
print('here')

输出

1
2
3
here

for循环没有遇到break语句,所以for循环结束后会接着执行else子句。无论您使用什么:

for i in 1,2,3:
print(i)
break
else:
print('here')

输出:

1

关于python-3.x - 为什么在 python 中允许 for else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54714955/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com