Here is a clear, simple, and exam-friendly explanation of Operator Precedence in Python, perfect for BCA/MCA/B.Tech students.
Operator Precedence in Python
Operator Precedence determines the order in which operators are evaluated in an expression.
When multiple operators appear together, Python does not evaluate them from left to right.
Instead, it follows a priority order known as precedence.
Example:
result = 10 + 5 * 2
This is not evaluated as (10 + 5) * 2 = 30
Correct evaluation based on precedence:
*has higher precedence than+- So:
5 * 2 = 10 - Then:
10 + 10 = 20
Output:
20
Why Precedence Matters?
It ensures expressions are evaluated correctly.
Without precedence rules, Python would produce incorrect or unpredictable results.
Complete Precedence Order in Python (Highest to Lowest)
Below is the standard precedence table used in Python (very useful for exams).
1. Parentheses – Highest Priority
()
Used to group expressions and override precedence.
Example:
(10 + 5) * 2 # 30
2. Exponentiation
**
Example:
2 ** 3 ** 2 # 2 ** (3 ** 2) = 2 ** 9 = 512
Exponent is right-associative.
3. Unary Operators
+, -, ~
Examples:
-5
+10
~3 # bitwise NOT
4. Multiplicative Operators
*, /, //, %
Example:
10 + 4 * 2 # 10 + 8 = 18
5. Additive Operators
+, -
Example:
10 - 3 + 2
6. Bitwise Shift Operators
<<, >>
Example:
8 >> 1 # 4
7. Bitwise AND
&
8. Bitwise XOR and OR
^
|
9. Comparison Operators
<, >, <=, >=, ==, !=, is, is not, in, not in
These evaluate to True/False.
10. Logical NOT
not
11. Logical AND
and
12. Logical OR – Lowest Precedence
or
Summary Table for Quick Revision
| Precedence Level | Operators | Priority |
|---|---|---|
| 1 | () | Highest |
| 2 | ** | Exponent |
| 3 | +x, -x, ~x | Unary |
| 4 | *, /, %, // | Multiplicative |
| 5 | +, - | Additive |
| 6 | <<, >> | Bitwise Shift |
| 7 | & | Bitwise AND |
| 8 | ^, ` | ` |
| 9 | <, >, <=, >=, ==, !=, is, in | Comparison |
| 10 | not | Logical NOT |
| 11 | and | Logical AND |
| 12 | or | Lowest |
Associativity Rules
Many operators have left-to-right associativity.
Examples:
Left to Right
+, -, *, /, %, //, <, >, & etc.
Right to Left
**, =, +=, -=
Example:
2 ** 3 ** 2
# evaluated as: 2 ** (3 ** 2)
Examples of Precedence in Practice
Example 1:
x = 10 + 4 * 2
Output:10 + 8 = 18
Example 2:
x = (10 + 4) * 2
Output:14 * 2 = 28
Example 3:
x = not True or False
# not True = False
# False or False = False
Example 4:
x = 5 and 0 or 3
# 5 and 0 = 0
# 0 or 3 = 3
Conclusion
Understanding operator precedence helps avoid mistakes in complex expressions.
You can always use parentheses () to make your expression clearer and override default precedence.
