在Python中,使用==
可以比较布尔值。但是当我应用布尔运算符not
时,结果会出现语法错误:
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True == True
True
>>> False == False
True
>>> True is not False
True
>>> True == not False
File "<stdin>", line 1
True == not False
^
SyntaxError: invalid syntax
>>>
为什么这是语法错误?我期望 not False
是一个返回布尔值的表达式,而且无论在哪里使用 <x>
都应该是有效的语法。
not
失败, 不论所比较的类型如何。例如:True < not False
,3 <= not 2
,'Foo' > not 'False'
,3.3 >= not 4.5
,{} is not not []
,set() == not None
和slice() != not lambda: x
都 会引发相同的语法错误。 这并不仅限于== not
和布尔值。 - Martijn Pieters