Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'True == not False' a syntax error in Python?

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.

like image 487
Tim Martin Avatar asked May 23 '11 16:05

Tim Martin


People also ask

Does == mean true in Python?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.

What are syntax errors in Python?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

Why is true and false false in Python?

In Python, the two Boolean values are True and False (the capitalization must be exactly as shown), and the Python type is bool. In the first statement, the two operands evaluate to equal values, so the expression evaluates to True; in the second statement, 5 is not equal to 6, so we get False.


1 Answers

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.

like image 53
Rafe Kettler Avatar answered Oct 18 '22 00:10

Rafe Kettler