blog
blog copied to clipboard
Python operators precedence rules
Precedence Rules
The order in which operators are evaluated in an expression is known as precedence rules.
Precedence rules for arithmetic, relational and logical operators:
Operator/Convention | Description | Explanation |
---|---|---|
( ) | Items within parentheses are evaluated first | In (a * (b + c)) - d , the + is evaluated first, then * , then - . |
* / % + - | Arithmetic operators (using their precedence rules) | z - 45 * y < 53 evaluates * first, then - , then < . |
< <= > >= == != | Relational, (in)equality, and membership operators | x < 2 or x >= 10 is evaluated as (x < 2) or (x >= 10) because < and >= have precedence over or . |
not | not (logical NOT) | not x or y is evaluated as (not x) or y |
and | Logical AND | x == 5 or y == 10 and z != 10 is evaluated as (x == 5) or ((y == 10) and (z != 10)) because and has precedence over or . |
or | Logical OR | x == 7 or x < 2 is evaluated as (x == 7) or (x < 2) because < and == have precedence over or |
Best Practices
A common error is to write an expression that is evaluated in a different order than expected. Good practice is to use parentheses in expressions to make the intended order of evaluation explicit.
For example, a programmer might write:
not x + y < 5
intending (not x) + y < 5
, but the interpreter computes not ((x + y) < 5)
because the addition operator +
has the highest precedence and is computed first,
followed by the relational operation <
,
and finally the logical not
operation.