Python 究竟如何计算由多个 and/or 运算符连接的语句?
当我在 Python 中运行以下语句时:
[1] or [] and (1,) or ()
输出为
[1]
。
但是对于以下声明,
[] or [1] and (1,) or ()
输出为
(1,)
。
我很困惑。是什么导致这两个语句的输出存在差异?这里的评估顺序是什么?
在 “or” 运算符中,当其中一个条件为真时,返回 “True” 如果两个条件都为假,则返回 “False”
所以你的第一个条件是: “[1] 或 [] 和 (1,) 或 ()”
When you separate the conditions one-by-one as:
**[1] or []**
It returns true as one of the condition is true.
with second condition in this
**[] and (1,)**
It will return false as one condition is true but it uses and operator.
with the third condition in this
**(1,) or ()**
It will return true as one of the condition is true.
If you put all the conditions together:
**"[1] or [] and (1,) or ()"**
We can expand it like
**"T or F and T"**
It will return **"True"** as it satisfied the **or** operator.
在 "and" 运算符中,当两个条件都为 true 时,它返回 "True" 如果其中一个条件为 false,则返回 "False"
你的第二个条件也一样 [] 或 [1] 和 (1,) 或 ()
Note: T for "True" F for "False"