OPM_OK
OPM_OK

Reputation: 190

IF Statement Formatting Python

I am trying to create a multiple layered IF statement and I am unsure if the statement below is correctly formatted.

I am having trouble reading the below nested IF statements, is it possible to write this code in a more efficient manner?

 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")

Upvotes: 1

Views: 199

Answers (2)

tgikal
tgikal

Reputation: 1680

While there may be a few reasons not to do this, execution time comes to mind, if readability of your nested if statements is that important to you, something like this works as well.

case_1 = case_2 = case_3 = False

try:
    case_1 = a >= gT and cLow > rBT
    case_2 = a_high > c_high and c_low < d_low and a > abc and a < c_low
    case_3 = min(a, b) > min(c, d) and max(e, f) > max(g, h)
except NameError:
   pass

if case_1:
    print("Alpha 1")
    if case_2:
        print("Final Count")
        if case_3:
            print("All Memory Deleted")

Upvotes: 1

PM 2Ring
PM 2Ring

Reputation: 55489

There's not a lot you can do to improve that, apart from making the indentation more uniform, removing redundant parentheses, combining the 2nd and 3rd if tests.

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")

The reason that it's safe to combine the 2nd and 3rd if tests is that the and operator "short-circuits", that is, in expression_1 and expression_2 if expression_1 is false then expression_2 is not evaluated. For more info on this topic, with examples (in Python 2), please see my answer here.


BTW, it's best to avoid backslash continuation if you can: it's too fragile. Any space after the backslash breaks the continuation. Instead, you can often wrap a long expression in parentheses, if it doesn't already use some form of bracket. Eg,

if (min(a, b) > min(c, d) and 
    max(e,f) > max(g, h)):

See the Python style guide PEP-0008 for further details.

Upvotes: 5

Related Questions