python - 比较运算符为 | 提供不同的值& 与 and or 相比 - Python

标签 python conditional-operator comparison-operators

我对比较运算符感到困惑。例如,

 10 or 20 == 20
 # output, expected True
 10

  10 | 20 == 20
 (10 | 20) == 20
 (10 or 20) == 20

所有 3 行代码都给出“False”,但我期待“True”。

 10 or 20 == 20
 # output gives 10, but was expecting True
 10

另一个例子:

 10 and 20 > 2
 # output is as expected
 True

 (10 and 20) > 2
 True

 (10 & 20) > 2
 # output gives False, but was expecting True
 False

最后,如果我这样做:

 10 or 20 > 100
 #output is 10. No idea why
 10
 3 or 8 < 200
 3

有人可以帮助解决这个困惑吗?非常感谢您花时间阅读我的困惑!我正在使用 Python 3.6

最佳答案

这两个条件运算符都会返回它们必须评估的最后一个条件或值。

or 运算符评估这两个条件中的任何一个是否为真,并返回最后评估的一个。由于 10 在 Python(或任何其他语言)中被认为是 True,因此该语言甚至不会执行第二个条件(或值),而只会返回第一个值。而在 and 的情况下,两个条件都必须为真,如果两者都为真,则返回第二个值,否则返回第一个值。

>>> True or False
True
>>> False or True
True
>>> True and False
False

# Similarly
>>> 10 or 20
10
>>> 10 and 20
20
>>> 0 or 10
10
>>> 0 and 10
0

此行为还为某些 b = a if a else c 类型的行为提供了便捷的替代方案。

关于python - 比较运算符为 | 提供不同的值& 与 and or 相比 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46446955/

相关文章:

Oracle NOT BETWEEN用于字符串比较的结果与<=和> =的结果不同

c++ - C++ 中的运算符调用语法

ruby - 在 Ruby 中按多个条件排序

python - 将数据框转换为字典

if-statement - if/else vs 三元运算符

c++ - 似乎无法让我的 IF 语句正常工作

c - 是否保证解析为 "(a ? b : (c ? d : e))"?

python - PIL Image.resize() 不调整图片大小

python - 用距点的距离填充numpy数组的最快方法

python - 为什么这些生成器表达式的行为不同?