python: try/except/else and continue 语句

标签 python python-2.7

为什么下面的 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/

相关文章:

python - 向 QTreeWidgetItem 切换复选框发出信号

python - Flask:登录 session 超时太快

python - 将数字转换为特殊的日期时间

python-2.7 - 在sklearn中使用datasets.fetch_mldata()时出现IO错误

python - CSV修改重复&算法 "paradox",在python中

python - boto3 定价客户端的区域名称和位置之间的映射

python - os.open vs open,使用什么

python - 使用 win32 从 Python 中的 Outlook Exchange 中提取发件人的电子邮件地址

python - 从字典中获取一个值并在 Python 中插入一个新字典

python - 在 python 中抛出 pdb 警告时如何查看函数内的变量?