In C/C++, comparison operators such as < >
have higher priority than ==
does. This code will evaluate to true
or 1
:
if(3<4 == 2<3) { //3<4 == 2<3 will evaluate to true
...
}
But in Python, it seems wrong:
3<4 == 2<3 #this will evaluate to False in Python.
In Python, does every comparison operator have the same priority?
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.
Almost all the operators have left-to-right associativity. For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first. Note: Exponent operator ** has right-to-left associativity in Python.
In Python, the left operand is always evaluated before the right operand. That also applies to function arguments. Python uses short circuiting when evaluating expressions involving the and or or operators.
Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.
In Python, not only do comparison operators gave the same priority, they are treated specially (they chain rather than group). From the documentation:
Formally, if
a, b, c, ..., y, z
are expressions andop1, op2, ..., opN
are comparison operators, thena op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... and y opN z
, except that each expression is evaluated at most once.
In your case, the expression
3<4 == 2<3
is equivalent to
3 < 4 and 4 == 2 and 2 < 3
which is False
due to the second clause.
Short answer: yeah, all the comparisons have the same precedence
Long answer: you may want to have a look on the documentation: Precedence on Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With