Python 3.x 使用3个或更多变量计算布尔逻辑

Python 3.x 使用3个或更多变量计算布尔逻辑,python-3.x,boolean,boolean-expression,Python 3.x,Boolean,Boolean Expression,当我计算三个布尔变量时,我试图理解Python的行为 >>真与真与假==假 符合事实的 计算结果为“True”,这正是我所期望的 然而 >>真与假和真==假 错误的 >>>False和True与True==False 错误的 当我期望为真时,两者的计算结果均为'False'。有人能帮我理解我在这里遗漏了什么吗。我尝试过搜索,但找不到在一条语句中计算3个布尔变量的示例 谢谢 这就是我能想到的解释 False and True and True == False False and True a

当我计算三个布尔变量时,我试图理解Python的行为

>>真与真与假==假
符合事实的
计算结果为“True”,这正是我所期望的

然而

>>真与假和真==假
错误的
>>>False和True与True==False
错误的
当我期望为真时,两者的计算结果均为'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)
好的,我已经解决了


“==”运算符具有优先权,并将首先求值

如果我将语句括在括号中,那么我将获得在发布的响应中指定的预期行为

带括号

Python 3.7.4(默认值,2019年8月13日,15:17:50)
[Clang 4.0.1(标签/发布\ U 401/最终版)]:达尔文的Anaconda公司
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>(真、真、假)=假
符合事实的
>>>(真与假与真)=假
符合事实的
>>>(假、真、真)=假
符合事实的
不带括号

>>真与真与假==假
符合事实的
>>>真与假,真==假
错误的
>>>False和True与True==False
错误的
>>> 

Ananth,你所描述的是我所期望的行为。但是,如果您在python控制台中输入“False和True以及True==False”,它将计算为“False”behaviour@ilmatic9000当然是假的,你能告诉我你不懂什么吗?没错,我帮你了吗?问题是我没有把左边的声明放在括号里。Python在计算“and”之前先计算了“==”,而“and”导致了我在第一篇文章中观察到的行为。是的,你帮助我确认了我对布尔运算的理解。e、 g.除了左侧的括号外,以下两个语句是相同的。第一个计算结果为“False”,第二个计算结果为“True”。>>False and True and True==False False>>>(False and True and True)==False TrueYes优先级和括号在此处起了作用“优先使用“==”运算符并首先进行求值”否,
=
最后延迟求值。您缺少的是布尔运算符“在顶部”(因为您通常希望例如
a==b和c==d
(a==b)和(c==d)
而不是
a==(b和c)==d
),因此
True和False以及True==False
被解析为
(True)和(False)以及(True==False)
,很明显,它是假的,而假的,而x必然是假的。马斯克林——因此,“真的、真的、假的==False”的语句被分解为1.“真的、真的”,2.“假的==False”。首先计算1.)和2.)的结果,然后将1.)和2.)的结果计算为“1.)和2.)返回“True”?