Mthokozisi Mhlongo
last year
Mthokozisicountry asked

If there are operators of the same precedence in an arithmetic operation, how do you evaluate it?

Kelish Rai
Expert
last year
Kelish Rai answered

When there are operators of the same precedence in an arithmetic operation, Python follows a specific rule called associativity to determine the order of evaluation.

Associativity defines the direction in which operations of the same precedence are processed:

  • Most arithmetic operators in Python (like +, -, *, /) are left-associative, meaning they are evaluated from left to right.

  • Some operators, like exponentiation (**), are right-associative, meaning they are evaluated from right to left.

Example 1: Left-to-right associativity (for - and /)

result = 20 - 5 - 2  # evaluated as (20 - 5) - 2 = 13
print(result)  # Output: 13

Example 2: Right-to-left associativity (for **)

result = 2 ** 3 ** 2  # evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512
print(result)  # Output: 512

If you're ever unsure, you can use parentheses to make the order of operations explicit. For example:

# Force a different order
result = (20 - (5 - 2))  # result is 17

If you want to learn more about this, I recommend checking out the blog Understanding Operator Precedence and Associativity in Python. It explains this concept in a clear and structured way.

Python
This question was asked as part of the Getting started with Python course.