Python

In Python, Operator Precedence determines the order in which expressions are evaluated when multiple operators are used in a single statement. Just as in mathematics (PEMDAS/BODMAS), certain operators have higher "priority" than others.

Understanding this is crucial to prevent logical errors where a calculation might result in a different value than expected.

1. Theoretical Overview

When an expression contains more than one operator, Python follows a specific hierarchy. Operators with higher precedence are evaluated first. If operators have the same precedence, Python evaluates them based on associativity (usually left-to-right).

The Hierarchy Table (Highest to Lowest)

PrecedenceOperatorDescription
1 (Highest)()Parentheses (used to force order)
2**Exponentiation (Power)
3+x, -x, ~xUnary plus, Unary minus, Bitwise NOT
4*, /, //, %Multiplication, Division, Floor Div, Modulus
5+, -Addition and Subtraction
6<<, >>Bitwise Shift operators
7&Bitwise AND
8^Bitwise XOR
9``
10==, !=, >, >=, <, <=Comparisons and Identity/Membership
11notLogical NOT
12andLogical AND
13orLogical OR
14 (Lowest)=, +=, -=, etc.Assignment operators

2. Associativity Rule

When two operators have the same precedence (like * and /), Python uses associativity:

  • Left-to-Right: Most operators (like +, -, *, /) are evaluated from left to right.

  • Right-to-Left: The Exponentiation operator (**) is evaluated from right to left.

    • Example: 2 ** 3 ** 2 is interpreted as $2^{(3^2)}$ which is $2^9 = 512$.

3. Code Implementation

Python
# Example 1: Basic Precedence
# Multiplication (*) before Addition (+)
res1 = 10 + 5 * 2 
print(f"10 + 5 * 2 = {res1}") # Output: 20

# Example 2: Using Parentheses to override
# Parentheses have the highest priority
res2 = (10 + 5) * 2
print(f"(10 + 5) * 2 = {res2}") # Output: 30

# Example 3: Division and Multiplication (Left-to-Right)
# (100 / 5) * 2 -> 20 * 2
res3 = 100 / 5 * 2
print(f"100 / 5 * 2 = {res3}") # Output: 40.0

# Example 4: Mixed Logical and Comparison
# Comparisons (>) happen before 'and'
res4 = 10 > 5 and 5 < 3
# True and False -> False
print(f"10 > 5 and 5 < 3 is {res4}") # Output: False

# Example 5: Exponentiation Right-to-Left
# 2 ** (3 ** 2) -> 2 ** 9
res5 = 2 ** 3 ** 2
print(f"2 ** 3 ** 2 = {res5}") # Output: 512

4. Best Practices

While knowing the table is important, relying on it too heavily can make code hard to read. Professional developers follow these rules:

  1. Use Parentheses: Even if not strictly necessary, use () to make the intent clear.

    • Better: (a * b) + c instead of a * b + c.

  2. Break it up: If an expression is too long, break it into multiple variables.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now