Don’t understand this boolean behalf of Python! Any explaination? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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

24th Oct 2018, 1:20 AM
Pela Lala
Pela Lala - avatar
4 Réponses
+ 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
24th Oct 2018, 5:04 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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!
24th Oct 2018, 7:00 AM
Pela Lala
Pela Lala - avatar
+ 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.
24th Oct 2018, 4:47 PM
Alex[]
Alex[] - avatar
+ 1
Yes, exactly!
24th Oct 2018, 7:23 AM
Kishalaya Saha
Kishalaya Saha - avatar