Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement with 2 variables and 4 conditions

I have 2 variables, say x and y, and I need to check which of them is None

if x is None and y is None:
    # code here
else:
    if x is not None and y is not None:
        # code here
    else:
        if x is None:
            # code here
        if y is None:
            # code here

Is there a better approach to do this?
I am looking for a shorter IF ELSE structure.

like image 580
Priyanka Khairnar Avatar asked Jan 01 '26 10:01

Priyanka Khairnar


1 Answers

Keeping the order you used:

if x is None and y is None:
    # code here for x = None = y
elif x is not None and y is not None:
    # code here for x != None != y
elif x is None:
    # code here for x = None != y
else:
    # code here for x != None = y

Modifying the order to reduce boolean evaluations:

if x is None and y is None:
    # code here for x = None = y
elif x is None:
    # code here for x = None != y
elif y is None:
    # code here for x != None = y
else:
    # code here for x != None != y

In a 4 case scenario, you should consider which of the options has a higher probability and which has the second higher and keep them the first two options, as this will reduce the amount of conditions checked during execution. The last two options will both execute the 3 conditions so the order of these two doesn't matter. For example the first code above considers that prob(x=None & y=None) > prob(x!=None & y!=None) > prob(x=None & y!=None) ~ prob(x!=None & y=None) while the second one considers that prob(x=None & y=None) > prob(x=None & y!=None) > prob(x!=None & y=None) ~ prob(x!=None & y!=None)

like image 177
Adirio Avatar answered Jan 03 '26 00:01

Adirio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!