当我评估三个布尔变量时,我试图理解 Python 的行为。
>>> True and True and False == False
True
评估为'True',这是我所期望的。
但是
>>> True and False and True == False
False
>>> False and True and True == False
False
当我期望 True 时,两者的评估结果都是 'False'。有人可以帮助我理解我在这里缺少什么吗?我尝试过搜索,但找不到在单个语句中计算 3 个布尔变量的示例。
谢谢!
这是我能想到的解释
False and True and True == False
False and True and False ( because True == False results in False)
(False and True) and False
False and False ( because 0 and 1 is 0)
False ( because 0 and 0 is 0)
True and False and True == False
True and False and False ( because True == False results in False)
(True and False) and False
False and False ( because 0 and 1 is 0)
False ( because 0 and 0 is 0)
它假设像三个输入和门表
A B C output
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 1
True and True and False == False # 0 and 0 and 0 the answer is 0 (False)
False and True and True == False # 0 and 1 and 0 the answer is 0 (False)
False and True and True == False # 0 and 1 and 0 the answer is 0 (False)
如果你想了解更多变量
True and True and True and True and False
# 1 and 1 and 1 and 1 and 0 output will be 0 (False)
# 1 * 1 * 1 * 1 * 0 output will be 0 (False)
True and True and True and True and True
# 1 and 1 and 1 and 1 and 1 output will be 1 (True)
# 1 * 1 * 1 * 1 * 1 output will be 1 (True)
True and False or True or True or True
# 1 and 1 or 1 or 1 or 1 output will be 1 (True)
# 1 * 1 + 1 + 1 + 1 output will be 1 (True)
好的,我已经解决了。
“==”运算符优先并首先被求值。
如果我将左侧的语句括在括号中,那么我会得到 https://stackoverflow.com/users/10384101/ananth-p
发布的响应中指定的预期行为带括号
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> (True and True and False) == False
True
>>> (True and False and True) == False
True
>>> (False and True and True) == False
True
不带括号
>>> True and True and False == False
True
>>> True and False and True == False
False
>>> False and True and True == False
False
>>>