Python follows a specific rule called operator precedence, which determines the order in which operations are executed in an expression.
Without precedence rules, Python would not know which operation to perform first.
🧠 What is Operator Precedence?
Operator precedence defines the order in which operators are evaluated in an expression.
👉 In simple words:
- It tells Python “what to solve first”
⚡ Example Without Understanding Precedence
result = 10 + 5 * 2
print(result)
👉 Output:
20
Why?
Because multiplication (*) has higher precedence than addition (+).
So:
- 5 * 2 = 10
- 10 + 10 = 20
⚙️ Python Operator Precedence Order
From highest to lowest:
| Priority | Operator |
|---|---|
| 1 | () Parentheses |
| 2 | ** Exponent |
| 3 | +x, -x, ~x Unary operators |
| 4 | * / // % Multiplication/Division |
| 5 | + - Addition/Subtraction |
| 6 | << >> Bitwise shift |
| 7 | & Bitwise AND |
| 8 | ^ Bitwise XOR |
| 9 | ` |
| 10 | == != > < >= <= Comparison |
| 11 | not Logical NOT |
| 12 | and Logical AND |
| 13 | or Logical OR |
🧪 Example 1: Mixed Operators
result = 10 + 5 * 2 ** 2
print(result)
Step-by-step:
- 2 ** 2 = 4
- 5 * 4 = 20
- 10 + 20 = 30
📦 Example 2: Using Parentheses
Parentheses always have the highest priority.
result = (10 + 5) * 2
print(result)
Output:
30
🔁 Example 3: Logical Operators
print(True or False and False)
Step-by-step:
-
andis evaluated first - False and False = False
- True or False = True
⚖️ Parentheses Override Precedence
You can control order using parentheses.
print((10 + 5) * (2 + 3))
🚀 Why Operator Precedence is Important?
Operator precedence is used in:
- Mathematical calculations ➗
- Decision-making logic 🧠
- Complex expressions ⚙️
- Programming conditions 🔁
🧾 Conclusion
Python operator precedence defines the order in which expressions are evaluated. Understanding it helps you write correct and predictable programs.
💡 Final Thought
If you master operator precedence, you can easily understand complex Python expressions without confusion.


0 Comments