如果不是没有,python将2个值相互求值

ugmeyewa  于 2023-01-27  发布在  Python
关注(0)|答案(2)|浏览(105)

是否可以进行求值,但仅限于两个值都不是None的情况?

foo=a
bar=a

if foo==bar:
  pass

但是只要foo和bar不是None,我就需要它,基本上如果两个值都是None,就不求值了?

yvgpqqbh

yvgpqqbh1#

只需使用is运算符将这些值与None进行比较:

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

rta7y2nd2#

您可以执行以下操作:

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

或通过应用德摩根定律:

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

相关问题