Operator precedence determines the order in which operations are performed in an expression. When multiple operators are used, Python follows a specific priority to evaluate them.
Operators with higher precedence are evaluated before operators with lower precedence.
| Precedence Level | Operators | Description |
|---|---|---|
| Highest | () |
Parentheses |
** |
Exponent | |
+x, -x |
Unary plus, minus | |
*, /, //, % |
Multiplication, Division | |
+, - |
Addition, Subtraction | |
==, !=, >, <, >=, <= |
Comparison | |
not |
Logical NOT | |
and |
Logical AND | |
| Lowest | or |
Logical OR |
()result = (2 + 3) * 4
print(result)
Output
20
Explanation
**print(2 + 3 ** 2)
Output
11
Explanation
3 ** 2 = 9, then 2 + 9 = 11print(10 + 2 * 3)
Output
16
print(10 - 2 + 3)
Output
11
print(5 + 2 > 6)
Output
True
print(True or False and False)
Output
True
Explanation
and has higher precedence than orFalse and False = FalseTrue or False = TrueWhen operators have the same precedence, associativity decides the order.
| Operator | Associativity |
|---|---|
** |
Right to left |
Most others (+, -, *) |
Left to right |
print(10 - 5 - 2)
Output
3
Explanation
(10 - 5) - 2print(2 ** 3 ** 2)
Output
512
Explanation
2 ** (3 ** 2) = 2 ** 9 = 512Even though Python has precedence rules, using parentheses is recommended.
result = (10 + 2) * 3
a = 5
b = 2
c = 3
result = a + b * c ** 2
print(result)
Output
23
Explanation
c ** 2 = 9b * 9 = 18a + 18 = 23and is evaluated before orOperator precedence defines the order of evaluation.
Higher precedence operators are evaluated first.
Key order:
() → ** → * / // % → + - → comparison → not → and → orAssociativity determines order when operators have equal priority.
Parentheses improve readability and correctness.