You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅当两个值均不为None时才执行相等性判断?

Solution

To meet your requirement—only running the equality check when both foo and bar are not None (and skipping the check if either or both are None), adjust your condition to first confirm neither value is None:

foo = a
bar = a

if foo is not None and bar is not None and foo == bar:
    pass

Explanation

  • foo is not None and bar is not None: This ensures both variables hold non-None values before proceeding to the equality check. Using is not None is Python's standard practice for verifying against the singleton None object.
  • The equality check foo == bar only executes when both values are non-None. If either (or both) is None, the entire condition evaluates to False, so the code inside the if block won't run.

If you prefer more readable structure, you can split the checks into nested conditions (this achieves the same result):

foo = a
bar = a

if foo is not None and bar is not None:
    if foo == bar:
        pass

内容的提问来源于stack exchange,提问作者dataviews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:45:42