Python Operator Precedence Explained with Examples (Easy Guide)
Operator Precedence in 🐍Python
Part 1: What is Operator Precedence in 🐍Python?
As we know there is Different Kind of Operators.Operator Precedence means the order in which the
Different Operators are Evaluated. We use Multiple Operator in a Single statement than they follow the Operator
Precedence Rule.In Simple Words Precedence means which Operator will solved first.
Example:
Input: 20-3*5
Step 1 3*5=15
Step 2 20-15=5
Output: 5
Part 2: Operator precedence (High to low)
| Parentheses | () | Example : 10-(3*5) 3*5=15 10-15 -5 |
| Exponent | Power, ** | Example : 100-(3**4) 3**4=81 100-81 19 |
| Multiplication, Division, Integer Division, Modulus | *, /, //, % |
Example : 20 + 6 * 4 / 2 // 3 % 5 Step 1: 6 * 4 = 24 20 + 24 / 2 // 3 % 5 Step 2: 24 / 2 = 12.0 20 + 12.0 // 3 % 5 Step 3: 12.0 // 3 = 4.0 20 + 4.0 % 5 Step 4: 4.0 % 5 = 4.0 20 + 4.0 Step 5: 20 + 4.0 = 24.0 |
| Addition, Subtraction | +,- | Example : 20+10-8 22 |
| Comparison Operator | ==, !=, <, >, <=, >= |
Example : a = 10 b = 5 a == b # False a != b # True a > b # True a < b # False a >= 10 # True b <= 5 # True |
| Logical Operator | And, Or, Not |
Example : x = 8 y = 3 print(x > 5 and y < 5) # True print(x < 5 or y < 5) # True print(not(x == y)) # True |
Part 3: Important Rules In Precedence of Python
- Parentheses override everything Example:Statement: 2*(7-3) ---> 2*4 --->8
- Same precedence → use associativity
- Most Operators: left → right Example : 2+3-4 -→→ 2+3=5 -→→ 5-4=1 -→→ 1
- Exception: ** , Power, Exponent : Right → Left Example : 2**3**2 →→ 3**2=9 →→ 2**9 = 512
- Logical Operator Precedence
When Multiple Logical Operator use in one Expression/Statment, Then they follow Some Order(High to Low).
NOT (!)
>HighestAND (&&)
>MiddleOR (||)
> LowestExample 1: True OR False →→ True Example 2: True OR True AND False →→ True AND False=False →→True OR False= True Example 3: Not True AND False OR True →→ NOT True=False →→ False AND False=False →→ False OR →→True= →→True
Part 4: How to learn in Easy way
Part 4.1: Think About the Video Game
Part 4.2: Easy Trick: The BODMAS Rule
| B | Brackets | "(5-2)" |
| O | Order | "5**2" |
| D | Division | "5/2" |
| M | Multiple | "5*2 |
| A | Addition | "5+2" |
| S | Subtraction | "5-2" |