As far as I know, in C & C++, the priority sequence for NOT AND & OR is NOT>AND>OR. But this doesn't seem to work in a similar way in Python. I tried searching for it in the Python documentation and failed (Guess I'm a little impatient.). Can someone clear this up for me?
Logical operators have operator precedence the same as other operators (relational, arithmetic, etc.). The highest precedence belongs to not , followed by and , and finally by or .
1 Expert AnswerThe AND (&&) does indeed come first, followed by the OR (||). Next, the OR statement is evaluated against the outcome of the previous AND.
There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English.
It's NOT, AND, OR, from highest to lowest according to the documentation on Operator precedence
Here is the complete precedence table, lowest precedence to highest. A row has the same precedence and chains from left to right
0. := 1. lambda 2. if – else 3. or 4. and 5. not x 6. in, not in, is, is not, <, <=, >, >=, !=, == 7. | 8. ^ 9. & 10. <<, >> 11. +, - 12. *, @, /, //, % 13. +x, -x, ~x 14. ** 14. await x 15. x[index], x[index:index], x(arguments...), x.attribute 16. (expressions...), [expressions...], {key: value...}, {expressions...}
You can do the following test to figure out the precedence of and
and or
.
First, try 0 and 0 or 1
in python console
If or
binds first, then we would expect 0
as output.
In my console, 1
is the output. It means and
either binds first or equal to or
(maybe expressions are evaluated from left to right).
Then try 1 or 0 and 0
.
If or
and and
bind equally with the built-in left to right evaluation order, then we should get 0
as output.
In my console, 1
is the output. Then we can conclude that and
has higher priority than or
.
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