使用 3 个或更多变量评估布尔逻辑

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

当我评估三个布尔变量时,我试图理解 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 个布尔变量的示例。

谢谢!

python-3.x boolean boolean-expression
3个回答
0
投票

这是我能想到的解释

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)

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)

0
投票

好的,我已经解决了。

“==”运算符优先并首先被求值。

如果我将左侧的语句括在括号中,那么我会得到 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
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.