Python 3中的德摩根定律

Python 3中的德摩根定律,python,python-3.x,logic,Python,Python 3.x,Logic,根据德摩根定律: ¬(P ˄ Q) ↔ (¬P) ˅ (¬Q) ¬(P ˅ Q) ↔ (¬P) ˄ (¬Q) 在Python 3.5中,当我运行时: A = True B = True x = not(A and B)==(not A) or (not B) y = not(A or B)==(not A) and (not B) print('x is :', x, '\ny is :' ,y) 这将返回: x is : True y is : False 问题:为什么y为False?

根据德摩根定律:

¬(P ˄ Q) ↔ (¬P) ˅ (¬Q)
¬(P ˅ Q) ↔ (¬P) ˄ (¬Q)
在Python 3.5中,当我运行时:

A = True
B = True
x = not(A and B)==(not A) or (not B)
y = not(A or B)==(not A) and (not B)
print('x is :', x, '\ny is :' ,y)
这将返回:

x is : True 
y is : False

问题:为什么y为False?

尝试添加一些括号--
=
的优先级高于

以下是您的建议尝试一下:

y = not(A or B)==((not A) and (not B))
它正在评估

not(A or B) == (not A)

首先。

操作人员的优先权让你绊倒。在Python中,
=
运算符的优先级高于
not
。表达式
nota==b
被理解为
not(a==b)
而不是
(nota)==b
,因为前者通常比后者更有用

因此,您的
y
应该如下所示:

y = (not(A or B)) == ((not A) and (not B))
x = (not(A and B)) == ((not A) or (not B))
您的
x
应该如下所示:

y = (not(A or B)) == ((not A) and (not B))
x = (not(A and B)) == ((not A) or (not B))
然后你会得到正确的结果。(你的
x
也是错误的,并且因为错误的原因得到了
True
的结果:它实际上是在评估
(不是((a和B)==(不是a))或者(不是B)
,结果是
(不是(真==假))或者是
真或假的
。但是你实际上想要的是
(不是)(A和B))==((不是A)或(不是B))
,其结果为
(非真)==(假或假)
,其结果为
False==False
。正如我所说,您的
x
由于错误的原因得到了
True
结果。)