Python Guide Sidebar

Operator Precedence in Python: the Order of Operations

Operator precedence determines the order in which Python evaluates expressions, and it plays a vital role in programming. When multiple operators are used in an expression, Python carefully follows specific rules to decide the sequence of operations. Furthermore, by understanding this hierarchy, you can ensure that your code is both clear and accurate. Additionally, it allows you to predict the outcome of complex expressions with confidence. Consequently, mastering operator precedence is essential for writing reliable and efficient Python programs.

Learn how operator precedence determines the order in which operations are performed in Python. Master how arithmetic, logical, and comparison operators interact with each other in expressions.

Table of Contents

  1. What is Operator Precedence?
  2. Why is Operator Precedence Important?
  3. Python Operators Precedence Table
  4. Associativity of Operators
  5. Practical Examples
  6. Mini-Project: Custom Calculator with Precedence
  7. Common Pitfalls and Best Practices
  8. Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho)

1. What is Operator Precedence?

Operator precedence is a set of rules that determines which operation gets evaluated first in an expression with multiple operators. Operators with higher precedence are evaluated before operators with lower precedence.

2. Why is Operator Precedence Important?

Operator precedence is critical for:

  • Preventing unintended results in calculations.
  • Writing code that is clear and predictable.
  • Minimizing errors in expressions with multiple operators.

For example:

result = 10 + 5 * 2
print(result)  # Output: 20 (Multiplication has higher precedence than addition)


3. Python Operators Precedence Table

Here’s the precedence hierarchy from highest to lowest:

Precedence LevelOperatorsDescription
1 (Highest)()Parentheses
2**Exponentiation
3+x, -x, ~xUnary plus, minus, bitwise NOT
4*, /, //, %Multiplication, division, modulo
5+, -Addition, subtraction
6<<, >>Bitwise shift
7&Bitwise AND
8^Bitwise XOR
9``
10==, !=, >, <, >=, <=, is, is notComparisons and identity operators
11notLogical NOT
12andLogical AND
13 (Lowest)orLogical OR

4. Associativity of Operators

Associativity defines the direction in which operators with the same precedence are evaluated:

  • Left-to-Right Associativity: Most operators (e.g., +, -, *, /) are evaluated from left to right.
  • Right-to-Left Associativity: Some operators (e.g., **, assignment operators) are evaluated from right to left.

Example:

print(2 ** 3 ** 2)  # Output: 512 (Right-to-left: 2 ** (3 ** 2))


5. Practical Examples

1: Combining Arithmetic and Logical Operators

result = 10 + 5 * 2 > 20 and 15 % 4 == 3
# Step-by-step evaluation:
# 1. 5 * 2 = 10 (multiplication first)
# 2. 10 + 10 = 20
# 3. 20 > 20 = False
# 4. 15 % 4 = 3
# 5. 3 == 3 = True
# 6. False and True = False

print(result)  # Output: False

2: Using Parentheses to Override Precedence

result = (10 + 5) * 2
print(result)  # Output: 30 (Parentheses alter the default order)

3: Operator Precedence with Boolean Logic

x = True or False and False
# Step-by-step evaluation:
# 1. False and False = False (AND has higher precedence than OR)
# 2. True or False = True

print(x)  # Output: True

6. Mini-Project: Custom Calculator with Precedence

Objective:

Create a calculator that respects operator precedence for arithmetic operations.

# Custom Calculator

def evaluate_expression(expression):
    try:
        result = eval(expression)
        return f"The result of '{expression}' is: {result}"
    except Exception as e:
        return f"Error: {e}"

# Test the calculator
expressions = [
    "10 + 5 * 2",
    "(10 + 5) * 2",
    "2 ** 3 ** 2",
    "100 / 5 + 20 - 3"
]

for expr in expressions:
    print(evaluate_expression(expr))

Output:

The result of '10 + 5 * 2' is: 20
The result of '(10 + 5) * 2' is: 30
The result of '2 ** 3 ** 2' is: 512
The result of '100 / 5 + 20 - 3' is: 37.0

7. Common Pitfalls and Best Practices

Pitfall 1: Ignoring Precedence

result = 10 + 5 * 2
print(result)  # Output: 20 (Not 30)

Pitfall 2: Overuse of Parentheses

While parentheses can override precedence, overusing them can make code cluttered.

# Avoid:
result = (((10 + 5) * 2) - (3 ** 2))
# Instead:
result = (10 + 5) * 2 - 3 ** 2

Best Practice: Always Use Parentheses for Clarity

Explicit parentheses improve readability and reduce errors.

result = (10 + 5) * 2


Interview Questions and Answers


Google

Q: What is the precedence of the not, and, and or operators?
A: The precedence order is:

  1. not (highest)
  2. and
  3. or (lowest)
    Example:
print(True or False and not False)  # Output: True

Amazon

Q: How does Python evaluate expressions with multiple ** operators?
A: Python evaluates ** operators from right to left (right-associative).

print(2 ** 3 ** 2)  # Output: 512

TCS

Q: Write a program to evaluate the following expression step by step: 100 / 2 + 3 ** 2 - 10
A:

# Step-by-step evaluation
expr = "100 / 2 + 3 ** 2 - 10"
result = eval(expr)
print(result)  # Output: 54.0

Infosys

Q: Why does 10 + 2 * 5 give 20 and not 60?
A: Multiplication (*) has higher precedence than addition (+). Python evaluates it as:

10 + (2 * 5) = 10 + 10 = 20

Zoho

Q: How can you use parentheses to alter operator precedence? Provide an example.
A: Parentheses explicitly define the evaluation order.

result = (10 + 2) * 5  # Output: 60


Conclusion

Understanding Python Operator Precedence is crucial because it allows you to write accurate and efficient code. Moreover, by mastering both precedence and associativity, you can evaluate complex expressions with confidence. In addition, this knowledge helps you avoid unexpected results and ensures your code behaves as intended. Ultimately, developing a strong grasp of operator precedence enables you to write cleaner, more reliable, and professional-grade Python programs.

operator procedence