尝试,带if的else子句除外

mas*_*lak 2 python if-statement exception python-3.x python-3.7

让我们想象一下这段代码:

    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
Run Code Online (Sandbox Code Playgroud)

如您所见,我重复了大量的说明(两者相同)。有没有一种避免重复的方法,但是与将代码放入函数中有所不同吗?

某种不同的逻辑还是使用finally还是尝试?我只是想不通。

在此先感谢您的帮助!

khe*_*ood 6

如果您不喜欢使用函数,那么如何在两个地方都设置一个变量,然后再检查它呢?

像这样:

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
Run Code Online (Sandbox Code Playgroud)