Practical – 150 : Determine the sequence of execution based on operator precedence
✅ Operator Precedence in Python: Execution Order
In Python, operator precedence determines the order in which operations are evaluated in an expression. Operators with higher precedence are evaluated before those with lower precedence.
🔢 Python Operator Precedence (High to Low)
|
Precedence |
Operators |
Description |
|
1 (highest) |
() |
Parentheses (Grouping) |
|
2 |
** |
Exponentiation |
|
3 |
+x, -x, ~x |
Unary plus, minus, bitwise NOT |
|
4 |
*, /, //, % |
Multiplication, Division, Modulus |
|
5 |
+, – |
Addition, Subtraction |
|
6 |
<<, >> |
Bitwise shift operators |
|
7 |
& |
Bitwise AND |
|
8 |
^ |
Bitwise XOR |
|
9 |
` |
` |
|
10 |
==, !=, >, <, >=, <=, is, in |
Comparisons |
|
11 |
not |
Logical NOT |
|
12 |
and |
Logical AND |
|
13 |
or |
Logical OR |
|
14 (lowest) |
=, +=, -=, etc. |
Assignment |
🧠Example to Understand Sequence:
result = 10 + 2 * 3 ** 2
Let’s break it step-by-step using operator precedence:
- ** (Exponentiation): 3 ** 2 = 9
- * (Multiplication): 2 * 9 = 18
- + (Addition): 10 + 18 = 28
✅ Output:
print(result)Â # Output: 28
📌 Example with Parentheses:
result = (10 + 2) * 3 ** 2
- () first: 10 + 2 = 12
- **: 3 ** 2 = 9
- *: 12 * 9 = 108
✅ Output:
print(result)Â # Output: 108
✅ Summary:
- Parentheses () override all precedence.
- Use parentheses to make expressions clear.
- Python follows standard math rules + adds logical and bitwise operator precedence.