Lessons
Courses

Operator Precedence in Python [ English ]

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

  • Ensures correct evaluation of expressions
  • Avoids ambiguity in calculations
  • Helps in writing accurate programs

3. Operator Precedence Table (High → Low)

Precedence LevelOperatorsDescription
Highest()Parentheses
**Exponent
+x, -xUnary plus, minus
*, /, //, %Multiplication, Division
+, -Addition, Subtraction
==, !=, >, <, >=, <=Comparison
notLogical NOT
andLogical AND
LowestorLogical OR

4. Explanation with Examples

4.1 Parentheses ()

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

Output

20

Explanation

  • Parentheses are evaluated first

4.2 Exponent **

print(2 + 3 ** 2)

Output

11

Explanation

  • 3 ** 2 = 9, then 2 + 9 = 11

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

  • and has higher precedence than or
  • So: False and False = False
  • Then: True or False = True

5. Associativity of Operators

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

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

Example

print(10 - 5 - 2)

Output

3

Explanation

  • Evaluated as: (10 - 5) - 2

Right-to-Left Example

print(2 ** 3 ** 2)

Output

512

Explanation

  • Evaluated as: 2 ** (3 ** 2) = 2 ** 9 = 512

6. Using Parentheses for Clarity

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

result = (10 + 2) * 3

7. Practical Example

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

Output

23

Explanation

  • c ** 2 = 9
  • b * 9 = 18
  • a + 18 = 23

8. Important Points

  • Parentheses have the highest priority
  • and is evaluated before or
  • Use parentheses to avoid confusion
  • Associativity determines order when precedence is same

9. Summary

  • Operator precedence defines the order of evaluation.

  • Higher precedence operators are evaluated first.

  • Key order:

    • ()*** / // %+ - → comparison → notandor
  • Associativity determines order when operators have equal priority.

  • Parentheses improve readability and correctness.