【发布时间】:2018-03-08 21:17:58
【问题描述】:
我对比较运算符感到困惑。例如,
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
【问题讨论】:
-
只需单独打印每个表达式,然后您就会了解它们组合的逻辑。例如,
(10 or 20)是 10,但(10 | 20)是 30。 -
10 & 20按位计算and,所以01010 & 10100(二进制)确实是00000,不大于2
标签: python conditional-operator comparison-operators