Ajay Chinni
Ajay Chinni

Reputation: 840

Best way to simplify multiple conditional statements

I have a single action to perform depending on the values of a,b,c,d but I may not get all the 4 values every time there will be 16 possible permutations I can get ϕ ,{a},{b},{c},{d},{a,b},{a,c},{a,d},{b,c},{b,d},{c,d},{a,b,c},{a,b,d},{a,c,d},{b,c,d},{a,b,c,d}.

def call_me (a=None,b=None,c=None,d=None):
    if a:
        a1 = a+1
    if b:
        b1 = b+2
    if c:
        c1 = c+3
    if d:
        d1 = d+4
    if (a<a1) and (b<b1) and (c<c1) and (d<d1):
        #Do something 
        return "something"

If I call call_me(a = 1,b = 2,c = 3,d =4) the program will work but in case If I do call_me(a = 1,b = 2,c = 3) it will throw me an error UnboundLocalError: local variable 'd1' referenced before assignment

So the only way I can think is to cover all the combinations (2 ^ N)

if a and b and c and d:
    if (a<a1) and (b<b1) and (c<c1) and (d<d1):
        return "something 1"

if a and b and c:
    if (a<a1) and (b<b1) and (c<c1):
        return "something 2"

if a and b and d:
    if (a<a1) and (b<b1) and (d<d1):
        return "something 3"
#and so on... 

Is there any way to simplify this by not using so many if statements?

Upvotes: 0

Views: 253

Answers (1)

tzaman
tzaman

Reputation: 47790

You can check for existence inside of each conditional where you're using the value:

if (a is None or a<a1) and (b is None or b<b1) and (c is None or c<c1) and (d is None or d<d1):
    # Do something

This way if any of the passed values is still None, that parenthesized expression will become True and won't interfere with the rest of the checks.


Another way to do it is to check the condition related to each variable at the same time as you check for existence, and just early-exit if it fails:

if a:
    a1 = a+1
    if not a<a1:
        return
if b:
    # etc.

# All conditions passed, do something. 

Upvotes: 1

Related Questions