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) * 4print(result)Output
20Explanation
**print(2 + 3 ** 2)Output
11Explanation
3 ** 2 = 9, then 2 + 9 = 11print(10 + 2 * 3)Output
16print(10 - 2 + 3)Output
11print(5 + 2 > 6)Output
Trueprint(True or False and False)Output
TrueExplanation
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
3Explanation
(10 - 5) - 2print(2 ** 3 ** 2)Output
512Explanation
2 ** (3 ** 2) = 2 ** 9 = 512Even though Python has precedence rules, using parentheses is recommended.
result = (10 + 2) * 3a = 5b = 2c = 3 result = a + b * c ** 2print(result)Output
23Explanation
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.