Eye*_*pie 1 python error-handling conditional-statements
例如,我的代码执行如下操作:
try:
for n in graph[x]:
#...
#...
if event == 0:
#do something
except IndexError:
#do the same thing
Run Code Online (Sandbox Code Playgroud)
我的if块和我的错误异常块具有相同的确切代码; 所以我没有冗余线,而是想要将两个块组合在一起.我想做一些像except IndexError or if target == 0:有条件的事情.这样做有一个聪明的方法吗?
最简单的,虽然有点hacky:改变你的
if event == 0:
#do something
Run Code Online (Sandbox Code Playgroud)
至
if event == 0:
raise IndexError
Run Code Online (Sandbox Code Playgroud)
以便"搔痒"以下except IndexError条款.
Cleaner就是在整个陈述之前把它do something变成一个内部函数defd try; 但在某些情况下确实需要更多的工作.
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |