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

为何Python中and/or运算符仅输出首个或第二个操作数?其逻辑是什么?

Python中and与or运算符的返回逻辑

Python里的and和or运算符遵循短路求值规则,并且会返回实际的操作数本身,而非统一返回布尔值True或False,这就是你看到这些输出的核心原因:

and运算符的逻辑

  • 若第一个操作数是假值(如0、""、False、None等),直接返回第一个操作数;
  • 若第一个操作数是真值(非假值的所有对象,比如非零数字、非空字符串、True等),则返回第二个操作数。

你给出的示例中所有操作数都是真值,因此都会返回第二个操作数:

>>> print(4 and 3)
3
>>> print(3 and 4)
4
>>> print(1 and True)
True
>>> print(True and 1)
1
>>> print(True and "hello")
hello

or运算符的逻辑

  • 若第一个操作数是真值,直接返回第一个操作数;
  • 若第一个操作数是假值,则返回第二个操作数。

你给出的示例中第一个操作数都是真值,因此都会返回第一个操作数:

>>> print(4 or 3)
4
>>> print(3 or 4)
3
>>> print(1 or True)
1
>>> print(True or 1)
True
>>> print(True or "hello")
True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:00:47