python - Try, except 子句 with if, else

标签 python python-3.x if-statement exception 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

如您所见,我重复了一大段指令(两者都相同)。 有没有办法避免重复,但与将代码放在函数中有所不同?

某种不同的逻辑或使用 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/

相关文章:

python - 嵌套列表代码中缺少第一个列表

python - 我们可以将数组/列表传递给 django 中的模板内容 block 吗? Python

python - 如何从文本文件中的一行转换日期和时间?

python-3.x - 使用predict_generator时如何返回项目的真实标签?

python - 如果在包根目录中,则无法导入 C++ 扩展

python - 我需要过滤或删除文件中的一些行

python - 在 Python 中为任意 n 嵌套 n 循环

if-statement - Google Sheets的查询+IFS函数

java - 我可以阻止我的程序打印重复信息吗

MySQL - IF/THEN 语句确定 INSERT INTO