+ 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 Respostas
+ 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!