Precedence of comparison and logical operators | Sololearn: Learn to code for FREE!
0

Precedence of comparison and logical operators

There is that one example in Introduction to Python, where it states that "You can put parentheses around the operations that should be done first. It makes the code easier to read." a = (3 > 2) or False Would it be correct, and is it possible to get into a situation, where evaluating a logical operation needs to precede the comparison operation, possibly in the same line? Are parentheses necessary in that case?

13th Jun 2024, 9:29 AM
Igor Matić
Igor Matić - avatar
6 Answers
+ 6
Comparison operators have higher precedence than Boolean operators so comparisons would be evaluated first. You may add parentheses to modify the evaluation. 2 == (3 and False) is a valid expression. It would first do (3 and False), which reduces to (False). Then it would compare 2 == False, which is False. In Booleans, any non-zero value is considered True. Zero is considered False. In the expression above, 3 is seen as True. And when using a Boolean in a mathematical expression, True gets promoted to integer 1, and False gets promoted to integer 0. print(5 + True) #outputs 6. --------- For a chart of operator precedence, see https://docs.python.org/3/reference/expressions.html#operator-precedence
13th Jun 2024, 5:36 PM
Brian
Brian - avatar
+ 5
Python would interpret numbers other than 0 as True (0 is False). so (3 and False) would become (True and False) which evaluates to False. Then it is 2 == False. False evaluates to 0 (True to 1), so that is interpreted as 2 == 0 which is False. so 2 == (3 and False) is False
14th Jun 2024, 2:07 AM
Bob_Li
Bob_Li - avatar
+ 3
Yes. Examine this logical expression without parentheses and with them: print(False and False or True) #True print(False and (False or True)) #False
13th Jun 2024, 2:36 PM
Brian
Brian - avatar
+ 2
Thanks, Brian and Bob_Li , that helped a lot.
14th Jun 2024, 4:51 AM
Igor Matić
Igor Matić - avatar
0
You i know that, i don't know how it transfers into domain of logical operations.
13th Jun 2024, 11:34 AM
Igor Matić
Igor Matić - avatar
0
That would mean that comparison operators need to be solved first in any case? 2 == 3 and False 2 == (3 and False) would not be correct and can't happen in a program?
13th Jun 2024, 3:54 PM
Igor Matić
Igor Matić - avatar