Python 中的 or/and 运算符究竟如何表现?

问题描述 投票:0回答:1

Python 究竟如何计算由多个 and/or 运算符连接的语句?

当我在 Python 中运行以下语句时:

[1] or [] and (1,) or ()

输出为

[1]

但是对于以下声明,

[] or [1] and (1,) or ()

输出为

(1,)

我很困惑。是什么导致这两个语句的输出存在差异?这里的评估顺序是什么?

python conditional-statements logical-operators
1个回答
0
投票

“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"

© www.soinside.com 2019 - 2024. All rights reserved.