Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 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
4 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!