mercredi 19 juin 2019

Better/simpler control flow for: if A, elif B, if A or B, else

I have the following control flow and I feel it can be improved but I lack the idea on how to...

I have two MUTUALLY EXCLUSIVE conditions and corresponding actions that need to be done condition specific (i.e. when that one is true) and condition unspecific (i.e. when either is true). Also I want to do something when neither condition is matched.

originally I had:

if condition1:
    print("something only on condition1")
    print("also this because any condition is True")
elif condition2:
    print("something only on condition2")
    print("also this because any condition is True")
else:
    print("do this when no condition")

however when the "print("also this because any condition is True")"-part is some large code block it seems impractical to repeat it. Thus I came up with

if condition1:
    print("something only on condition1")
elif condition2:
    print("something only on condition2")
if condition1 or condition2:
    print("also this because any condition is True")
else:
    print("do this when no condition")

this however feels somewhat overkill. Since both conditions have already been checked individually, the condition with the "or" statement seems unnecessarily redundant. I might be mistaken though.

An third alternative would be

if condition1 or condition2:
    if condition1:
        print("something only on condition1")
    elif condition2:
        print("something only on condition2")
    print("also this because any condition is True")
else:
    print("do this when no condition")

however this is also no real improvement and I feel that the stacked if statements are even harder to comprehend fast.

Also I need to keep in mind that I want the "also this because any condition is True" to be run after any of the condition specific actions.

My goal/question is if there is a smart way to simplify this control flow and to make it easily understood. For example a way to only have 3 control blocks (if, elif, else) or in general to only evaluate each individual condition once.

Thank you :)

Aucun commentaire:

Enregistrer un commentaire