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 '='.)
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 .
Python Equal To (==) Operator The equal to operator returns True if the values on either side of the operator are equal.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.
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, sonot a == b
is interpreted asnot (a == b)
, anda == not b
is a syntax error.
Basically, the interpreter thinks you're comparing True
to not
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With