Home > Software design >  python evaluate 2 values to eachother if not none
python evaluate 2 values to eachother if not none

Time:01-26

Is it possible to do an evaluation, but only if both values aren't None?

foo=a
bar=a

if foo==bar:
  pass

But I need it as long as foo and bar are not None. Basically if both values are None, don't do the evaluation?

CodePudding user response:

Just compare the values to None with the is operator:

if (foo is None) or (bar is None):
    print("skip comparison")
elif condition(foo, bar):
    print("done comparison")

CodePudding user response:

You can do this:

if not (foo is None and bar is None):
    # do something

or by applying de Morgan's Laws:

if foo is not None or bar is not None:
    # do something
  • Related