让我们想象一下这段代码:
try:
if condition1 and condition2: # some_exception may happen here
function1()
elif condition3 and condition4: # some_exception may happen here
function2()
else:
big
block
of
instructions
except some_exception:
big
block
of
instructions
如您所见,我重复了一大段指令(两者都相同)。 有没有办法避免重复,但与将代码放在函数中有所不同?
某种不同的逻辑或使用 finally 或 else 来尝试?我就是想不通。
在此先感谢您对我的帮助!
最佳答案
如果您不喜欢使用函数,那么在两个地方都设置一个变量,然后再检查一下怎么样?
像这样:
do_stuff = False
try:
if condition1 and condition2: # some_exception may happen here
function1()
elif condition3 and condition4: # some_exception may happen here
function2()
else:
do_stuff = True
except some_exception:
do_stuff = True
...
if do_stuff:
big
block
of
instructions
关于python - Try, except 子句 with if, else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170422/