我对比较运算符感到困惑。例如,
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/