Precedence of Logical Operators (NOT, AND, OR) in Python
Contrary to C and C where precedence of logical operators follows the sequence NOT > AND > OR, Python's precedence may seem confusing.
Clarification
In Python, the precedence sequence for logical operators is actually:
NOT > AND > OR
This means that NOT has higher precedence than AND, while AND has higher precedence than OR.
Precedence Table
For a comprehensive understanding of operator precedence in Python, here is the complete precedence table:
Precedence | Operator | |
---|---|---|
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 | **, await x | |
15 | x[index], x[index:index], x(arguments...), x.attribute | |
16 | (expressions...), [expressions...], {key: value...}, {expressions...} |
Example
Consider the following expression:
x = not (a or b) and c
Using the precedence table, we evaluate the expression as follows:
The above is the detailed content of How does Python's logical operator precedence differ from C and C ?. For more information, please follow other related articles on the PHP Chinese website!