Notes
Categories

Operator Precedence in Python [ English ]

< Prev Next >

1. Introduction

Operator precedence determines the order in which operations are performed in an expression. When multiple operators are used, Python follows a specific priority to evaluate them.

Operators with higher precedence are evaluated before operators with lower precedence.

2. Importance of Operator Precedence

3. Operator Precedence Table (High → Low)

Precedence Level Operators Description
Highest () Parentheses
** Exponent
+x, -x Unary plus, minus
*, /, //, % Multiplication, Division
+, - Addition, Subtraction
==, !=, >, <, >=, <= Comparison
not Logical NOT
and Logical AND
Lowest or Logical OR

4. Explanation with Examples

4.1 Parentheses ()

result = (2 + 3) * 4
print(result)

Output

20

Explanation

4.2 Exponent **

print(2 + 3 ** 2)

Output

11

Explanation

4.3 Multiplication and Division

print(10 + 2 * 3)

Output

16

4.4 Addition and Subtraction

print(10 - 2 + 3)

Output

11

4.5 Comparison Operators

print(5 + 2 > 6)

Output

True

4.6 Logical Operators

print(True or False and False)

Output

True

Explanation

5. Associativity of Operators

When operators have the same precedence, associativity decides the order.

Operator Associativity
** Right to left
Most others (+, -, *) Left to right

Example

print(10 - 5 - 2)

Output

3

Explanation

Right-to-Left Example

print(2 ** 3 ** 2)

Output

512

Explanation

6. Using Parentheses for Clarity

Even though Python has precedence rules, using parentheses is recommended.

result = (10 + 2) * 3

7. Practical Example

a = 5
b = 2
c = 3

result = a + b * c ** 2
print(result)

Output

23

Explanation

8. Important Points

9. Summary

< Prev Next >