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.


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)


  def func1(a):
    print a
  def func2(a):
    print a
  def func3(a):
    print a
  def func4(a):
    print a

  options = {(1, 1): func1,
                (1, 0): func2,
                (0, 1): func3,
                (0, 0): func4,}

  options[(True, True)](100)

输出:

100

If you need 4 different paths for each of the possible combination of x and y , you can't really simplify it that much. That said, I would group the checks for one of the variables (ie check if x is None first, then inside, check if y is None .)

Something like this:

if x is None:
    if y is None:
        # x is None, y is None
    else:
        # x is None, y is not None
else:
    if y is None:
        # x is not None, y is None
    else:
        # x is not None, y is not None
链接地址: http://www.djcxy.com/p/76640.html

上一篇: 如何检查任意对象是否为'None'?

下一篇: IF语句有2个变量和4个条件