The following code outputs False, when according to the Python Order of Operations it should output True (the order should be in -> ==, not the other way around). Why is == coming before in?
y = "33"
"3" in y == True
Output
False
The existing answers give helpful advice that you shouldn't compare booleans to True
because it's redundant. However, none of the answers actually answer the root question: "why does "3" in y == True
evaluate to False
?".
That question was answered in a comment by juanpa.arrivillaga:
Also, this is an instance of operator chaining, since
==
andin
both count as comparison operators. So this is evaluated as('3' in y) and (y == True)
In Python, comparison operators can be chained. For example, if you want to check that a
, b
, c
, and d
are increasing, you can write a < b < c < d
instead of a < b and b < c and c < d
. Similarly, you can check that they are all equal with a == b == c == d
.
Chained comparisons are described in the Python documentation here:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
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