gpt4 book ai didi

python: try/except/else and continue 语句

转载 作者:太空狗 更新时间:2023-10-29 21:38:51 28 4
gpt4 key购买 nike

为什么下面的 python 代码片段的输出NOT只是No exception:1,因为在第一次迭代期间没有引发异常。来自 python 文档(https://docs.python.org/2.7/tutorial/errors.html)。

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

$ cat hello.py
for x in range(1,10):
try:
if x == 1:
continue
x/0
except Exception:
print "Kaput:%s" %(x)
else:
print "No exception:%s" %(x)
break

$ python hello.py
Kaput:2
Kaput:3
Kaput:4
Kaput:5
Kaput:6
Kaput:7
Kaput:8
Kaput:9

$ python -V
Python 2.7.8

最佳答案

教程提供了一个良好的开端,但不是语言引用。 Read the reference here.

特别注意:

The optional else clause is executed if and when control flows off the end of the try clause.

由脚注 2 阐明:

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

因此,您对 continue 的使用已明确解决。

关于python: try/except/else and continue 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816459/

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