IF语句格式化Python

OPM*_*_OK 1 python if-statement

我正在尝试创建一个多层IF语句,我不确定下面的语句是否正确格式化.

我在阅读下面嵌套的IF语句时遇到问题,是否可以更有效地编写此代码?

谢谢,

 if (a>= gT) and (cLow> rBT):
            print("Alpha 1")


            if (a_high> c_high) and (c_low < d_low):
                if (a> abc) and (a< c_low):
                    print("Final Count")

                    if (min(a, b) > min(c, d)) and \
                            (max(e,f) > max(g, h)): print("All Memory Deleted")
Run Code Online (Sandbox Code Playgroud)

PM *_*ing 5

除了使缩进更均匀,删除多余的括号,组合第二次和第三次if测试之外,你可以做很多事情来改进它.

if a >= gT and cLow > rBT:
    print("Alpha 1")
    if a_high > c_high and c_low < d_low and a > abc and a < c_low:
        print("Final Count")
        if min(a, b) > min(c, d) and max(e,f) > max(g, h):
            print("All Memory Deleted")
Run Code Online (Sandbox Code Playgroud)

它是安全的,2楼和3相结合的原因if的测试是,and操作人员"短路",也就是说,在expression_1 and expression_2如果expression_1是假,则expression_2进行评估.有关此主题的更多信息,请参阅示例(在Python 2中),请在此处查看我的答案.


顺便说一下,如果可以的话,最好避免反斜杠延续:它太脆弱了.反斜杠后的任何空格都会破坏延续.相反,如果它还没有使用某种形式的括号,你通常可以在括号中包含一个长表达式.例如,

if (min(a, b) > min(c, d) and 
    max(e,f) > max(g, h)):
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅Python样式指南PEP-0008.