40
votes

Comparing boolean values with == works in Python. But when I apply the boolean not operator, the result is a syntax error:

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
>>> 

Why is this a syntax error? I would expect not False to be an expression that returns a boolean value, and True == <x> to be valid syntax wherever <x> is an expression with valid syntax.

3
Note, that "True is not False" is not the same as "True is (not False)". "is not" is a distinct operator, which means "is not identical to", whereas "True is (not False)" reads as "True is identical to the boolean negation of False". Just a remark, because your example seems, as if you would assume, that both of these are the same. - lunaryorn
True == not is the actual syntax error, anything after that is irrelevant. - dansalmo
And for the record, this fails for any comparison operator plus not, regardless of the types compared. True < not False, 3 <= not 2, 'Foo' > not 'False', 3.3 >= not 4.5, {} is not not [], set() == not None and slice() != not lambda: x all raise the same syntax error. This is not limited to == not and booleans. - Martijn Pieters♦

3 Answers

55
votes

It has to do with operator precedence in Python (the interpreter thinks you're comparing True to not, since == has a higher precedence than not). You need some parentheses to clarify the order of operations:

True == (not False)

In general, you can't use not on the right side of a comparison without parentheses. However, I can't think of a situation in which you'd ever need to use a not on the right side of a comparison.

10
votes

It's just a matter of operator precedence. Try:

>>> True == (not False)
True

Have a look in this table of operator precedences, you'll find that == binds tigher than not, and thus True == not False is parsed as (True == not) False which is clearly an error.

-1
votes

I think what you are looking for is "and not". This gives you the results you are looking towards. If your comparing booleans what you have is a compound boolean expression, here is an example website Compound Boolean Expression.

>>> True and True
True
>>> True and not True
False
>>> True and not False
True
>>> False and not True
False
>>> False and not False
False
>>> False and False
False