3.2 Operator Precedence and Associativity (BT101CO)

When multiple operators appear in a single expression, Python follows a specific order of priority to decide which calculation to perform first. This rule is similar to BODMAS or PEMDAS in mathematics.

1. Operator Precedence (The hierarchy)

The hierarchy of operations is as follows (from highest priority to lowest):

  1. Parentheses (): Highest priority. Anything inside parentheses is calculated first.
  2. Exponentiation **: Power calculations come second.
  3. Multiplication, Division, Floor Division, Modulus *, /, //, %: These are evaluated third, from left to right.
  4. Addition, Subtraction +, -: These are evaluated last, from left to right.

Example:

result = 10 + 2 * 3 ** 2
# 1. Power first: 3 ** 2 = 9
# 2. Multiply second: 2 * 9 = 18
# 3. Add last: 10 + 18 = 28
print(result) # Output: 28

2. Understanding Associativity

What happens when two operators have the same level of priority? This is where associativity comes in. It determines whether the expression is evaluated from left to right or right to left.

  • Left-to-Right Associativity: Most operators in Python are left-associative.
    Example: 100 / 10 * 2(100 / 10) * 220.0
  • Right-to-Left Associativity: The exponentiation operator (**) is right-associative.
    Example: 2 ** 3 ** 22 ** (3 ** 2)2 ** 9512

Practice Quiz