+ 4
Don’t understand this boolean behalf of Python! Any explaination?
“”” The interesting is that: in the boolean expression a == 3 > 1, I don’t know which operator, ‘==‘ or ‘>’ is the priority. To figure out, I try to put parenthesis in the expression to make custom priority, but the outcome is too much confusing! “”” a = 3 print(a == 3 > 1) # True print((a == 3) > 1) # False print(a == (3 > 1)) # False
5 ответов
+ 4
tl;dr version: a == 3 > 1 is a chained comparison equivalent to (a == 3 and 3 > 1). Which is True.
_____
Long answer: I'll start with the later two.
print((a == 3) > 1) # False
a == 3 is True. True is not greater than 1. False. (True == 1. A boolean and an integer can be compared, no problem. You can verify my claim by doing print((a == 3) == 1). Output is True.)
print(a == (3 > 1)) # False
3 > 1 is True. a is not equal to True. False.
Now, the main problem. First, the operators "==" and ">" have the same precedence ( https://docs.python.org/3/reference/expressions.html#operator-precedence ). This may lead us to think that they should be evaluated left-to-right like (a == 3) > 1, but that is NOT the case. This is actually a chained comparison ( https://docs.python.org/3/reference/expressions.html#comparisons )! It is equivalent to
a == 3 and 3 > 1
Since both a == 3 and 3 > 1 are True, the result is True. Another example of a chained comparison:
print(1 < a < 4) # True
+ 2
Thank you both, THE TRUMP and Kishalaya Saha! I have read the python documentation and know that the expression ‘a == 3 > 1’ is a special comparison called ‘arbitrarily chained comparison’.
Here is the documentation text explaining that special kind of comparison technically:
“Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.”
Hence, ‘a == 3 > 1’ is equivalent to ‘(a == 3) and (3 > 1)’. In this case it is ‘True and True’ which is True, of course!
+ 2
look any boolean value equal to 1 or above it is true (1). so first 3>1 results true (1). but then, recursevely 1 is not greater than 1, so returns false.
+ 1
Yes, exactly!