23

I'm learning about comparison operators, and I was playing around with True and False statements. I ran the following code in the Python shell:

not(5>7) == True

As expected, this returned True. However, I then ran the following code:

True == not(5>7)

and there was a syntax error. Why was this? If the first line of code is valid syntax, then surely the second line of code should also be valid. Where have I gone wrong?

(To give a bit of background, my understanding is that = in Python is only used for variable assignment, while == is closely related to the mathematical symbol '='.)

Joe
  • 351
  • 2
  • 10

1 Answers1

33

The syntax error seems to be caused by the not keyword, not (pun intended) the equality operator:

True == not (5 > 7)
# SyntaxError: invalid syntax
True == (not (5 > 7))
# True

The explanation can be found in the docs:

not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

Basically, the interpreter thinks you're comparing True to not.

adamgy
  • 4,543
  • 3
  • 16
  • 31
  • Right, so `not(5>7) == True` boils down to `not(False) == True` (no problem here), whereas `True == not(5>7)` boils down to `True == not(False)`, and because `True` and `not` are adjacent to each other, the problem which you have described occurs. Do I understand correctly? – Joe Jul 12 '20 at 17:57
  • 2
    True == not(5 > 7) boils down to (True == not) (False), in which case the first statement obviously makes no sense. – adamgy Jul 12 '20 at 18:15
  • Ok, thank you. This was a very insightful answer. – Joe Jul 12 '20 at 18:21
  • 1
    To expand a bit on this or make it more explicit: `not` is an operator (similar to a unary `-` operator), not a function like `abs` as `not(...)` seems to imply. The brackets are not required for the `not` itself and they are only necessary if you want to enforce the order in which operators are evaluated. @Joe – Bernhard Barker Jul 13 '20 at 06:40
  • 8
    @Joe: `not(5>7) == True` boils down to `not (False == True)`. `not` is not a function, and the parentheses and lack of spacing in `not(5>7)` are misleading. This kind of confusion is one of the primary reasons not to treat keywords as if they were functions. – user2357112 Jul 13 '20 at 07:06