Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does equality not appear to be a symmetric relation in Python? [duplicate]

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 '='.)

like image 981
Joe Avatar asked Jul 12 '20 17:07

Joe


People also ask

How do you define equality in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

Does Python have equal?

Python Equal To (==) Operator The equal to operator returns True if the values on either side of the operator are equal.

Are there other special python methods that you can use to do equality comparison?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.


1 Answers

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.

like image 76
adamgy Avatar answered Oct 23 '22 21:10

adamgy