Python Operator Precedence
1. What is Operator Precedence?
Operator precedence means which operator Python runs first when there are many operators in one line.
In simple words:
👉 It is the order of calculation.
Just like math:
-
Multiply before add
-
Divide before subtract
Python follows similar rules.
2. Simple Example
Look at this code:
print(10 + 5 * 2)
Output:
20
Why?
-
5 * 2is done first →10 -
Then
10 + 10→20
3. Using Brackets (Parentheses)
Brackets () have highest priority.
Example
print((10 + 5) * 2)
Output:
30
Here:
-
10 + 5is done first →15 -
Then
15 * 2→30
4. Basic Operator Precedence Order (Easy List)
From highest priority to lowest:
-
()– Brackets -
**– Power -
* / // %– Multiply, Divide -
+ -– Add, Subtract -
Comparison (
> < == !=) -
Logical (
and,or,not)
5. Power vs Multiply
Example
print(2 ** 3 * 2)
Output:
16
Explanation:
-
2 ** 3→8 -
8 * 2→16
6. Multiply vs Add
Example
print(5 + 3 * 4)
Output:
17
7. Comparison Precedence
Example
print(10 > 5 + 3)
Output:
True
Explanation:
-
5 + 3→8 -
10 > 8→True
8. Logical Operator Precedence
Example
print(True or False and False)
Output:
True
Explanation:
-
andruns beforeor -
False and False→False -
True or False→True
9. Use Brackets to Avoid Confusion
Best practice:
👉 Always use () to make code clear.
Example
result = (10 + 5) * (2 + 3)
print(result)
10. Common Beginner Mistakes
❌ Assuming Left to Right Always
print(10 + 2 * 3)
Wrong expectation: 36
Correct answer: 16
❌ Forgetting Brackets
result = 10 + 5 * 2
Better:
result = (10 + 5) * 2
11. Simple Practice Examples
Example 1
print(8 + 2 * 5)
Example 2
print((8 + 2) * 5)
Example 3
print(10 > 3 and 5 > 2)
12. Summary (Operator Precedence)
✔ Precedence decides calculation order
✔ Brackets () run first
✔ Power before multiply
✔ Multiply before add
✔ Use brackets for clarity
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School students
-
Self-learners
If you want next, I can write:
-
if–else statements (easy)
-
Loop concepts
-
Operator exercises
-
MCQs with answers
Just tell me 😊
