🎯 Operator Precedence
Operator precedence determines the order in which Python evaluates different operators in complex expressions. Understanding precedence helps you predict how your code will behave and write expressions that work as intended. When multiple operators appear in the same expression, Python follows specific rules to decide which operations to perform first.
Think of operator precedence like the order of operations in mathematics - multiplication happens before addition unless you use parentheses to change the order. Python follows similar rules for all its operators.
# Operator precedence in action
result1 = 2 + 3 * 4
print(f"2 + 3 * 4 = {result1}") # 14 (multiplication first)
result2 = (2 + 3) * 4
print(f"(2 + 3) * 4 = {result2}") # 20 (parentheses change order)
result3 = 10 > 5 and 3 < 7
print(f"10 > 5 and 3 < 7 = {result3}") # True (comparisons before logical)
result4 = 2 ** 3 * 4
print(f"2 ** 3 * 4 = {result4}") # 32 (exponentiation first)
🏗️ Understanding Precedence Levels
Python operators are organized into precedence levels, with higher precedence operators evaluated before lower precedence ones. When operators have the same precedence, Python evaluates them from left to right (left-associative) in most cases.
# Different precedence levels
x = 5
y = 10
z = 15
# Arithmetic before comparison
result1 = x + y > z
print(f"{x} + {y} > {z} = {result1}") # False (15 > 15 is False)
# Comparison before logical
result2 = x < y and y < z
print(f"{x} < {y} and {y} < {z} = {result2}") # True (both comparisons true)
# Complex expression with multiple precedence levels
result3 = 2 + 3 * 4 > 10 and not False
print(f"2 + 3 * 4 > 10 and not False = {result3}") # True
🧮 Arithmetic Operator Precedence
Arithmetic operators follow the familiar mathematical order: exponentiation has the highest precedence, followed by multiplication and division, then addition and subtraction. This matches what you learned in math class.
# Arithmetic precedence examples
print("=== ARITHMETIC PRECEDENCE ===")
result1 = 2 + 3 * 4 ** 2
print(f"2 + 3 * 4 ** 2 = {result1}") # 50 (4²=16, 3×16=48, 2+48=50)
result2 = -3 ** 2
print(f"-3 ** 2 = {result2}") # -9 (exponentiation before negation)
result3 = (-3) ** 2
print(f"(-3) ** 2 = {result3}") # 9 (parentheses change order)
# Remember: multiplication before addition
result4 = 2 + 3 * 4
print(f"2 + 3 * 4 = {result4}") # 14 (not 20)
🤔 Comparison and Logical Precedence
Comparison operators have lower precedence than arithmetic operators but higher precedence than logical operators. This allows you to write natural expressions like x + 1 > y and z < 10
without extra parentheses.
# Comparison and logical precedence
print("=== LOGICAL PRECEDENCE ===")
a = 5
b = 10
c = 15
# Arithmetic, then comparison, then logical
result1 = a + 5 > b and c - 5 < b
print(f"{a} + 5 > {b} and {c} - 5 < {b} = {result1}") # True
# NOT has highest logical precedence
result2 = not a > b or c > b
print(f"not {a} > {b} or {c} > {b} = {result2}") # True
# Remember: NOT before AND
result3 = not True and False
print(f"not True and False = {result3}") # False
# Exercise example: multiple precedence levels
result4 = 2 + 3 * 4 > 10 and not False
print(f"2 + 3 * 4 > 10 and not False = {result4}") # True
📋 Complete Precedence Table
Here's the complete precedence order from highest to lowest, with the operators you'll use most often:
Precedence | Operators | Description | Example |
---|---|---|---|
1 (Highest) | () | Parentheses | (2 + 3) * 4 |
2 | ** | Exponentiation | 2 ** 3 |
3 | +x , -x , not x | Unary operators | -5 , not True |
4 | * , / , // , % | Multiplication, division | 3 * 4 |
5 | + , - | Addition, subtraction | 5 + 2 |
6 | == , != , < , > , <= , >= | Comparisons | x == y |
7 | not | Logical NOT | not True |
8 | and | Logical AND | True and False |
9 (Lowest) | or | Logical OR | True or False |
🔧 Using Parentheses for Clarity
Even when you know the precedence rules, using parentheses makes your code more readable and prevents mistakes. Parentheses have the highest precedence and can override the default evaluation order.
# Using parentheses for clarity
print("=== PARENTHESES FOR CLARITY ===")
# Without parentheses - relies on precedence
result1 = 5 + 3 * 2 > 10 or 4 < 6
print(f"5 + 3 * 2 > 10 or 4 < 6 = {result1}") # True
# With parentheses - makes intent clear
result2 = ((5 + 3) * 2) > 10 or (4 < 6)
print(f"((5 + 3) * 2) > 10 or (4 < 6) = {result2}") # True (different calculation!)
# Complex expression made clear
age = 25
income = 50000
has_job = True
credit_score = 750
# Without parentheses (works but unclear)
eligible1 = age >= 18 and income > 30000 or has_job and credit_score > 700
# With parentheses (clear intent)
eligible2 = (age >= 18 and income > 30000) or (has_job and credit_score > 700)
print(f"Loan eligible: {eligible2}") # True
📐 Quick Precedence Practice
Let's practice understanding how Python evaluates expressions with multiple operators!
Hands-on Exercise
Practice understanding operator precedence and using parentheses to control evaluation order.
# Precedence Practice - Order matters!
# Calculate without parentheses (following precedence rules)
result1 = 2 + 3 * 4 # What happens first: + or *?
# Calculate with parentheses (force different order)
result2 = (2 + 3) * 4 # Force addition to happen first
# Complex expression with comparison
age = 25
result3 = age + 5 > 25 # Math first, then comparison
print(f"2 + 3 * 4 = {result1}")
print(f"(2 + 3) * 4 = {result2}")
print(f"age + 5 > 25 = {result3}")
Solution and Explanation 💡
Click to see the complete solution
# Precedence Practice - Simple solution
# Calculate without parentheses (following precedence rules)
result1 = 2 + 3 * 4 # Multiplication first: 2 + 12 = 14
# Calculate with parentheses (force different order)
result2 = (2 + 3) * 4 # Addition first: 5 * 4 = 20
# Complex expression with comparison
age = 25
result3 = age + 5 > 25 # Math first (25 + 5 = 30), then comparison (30 > 25 = True)
print(f"2 + 3 * 4 = {result1}") # 14
print(f"(2 + 3) * 4 = {result2}") # 20
print(f"age + 5 > 25 = {result3}") # True
Key Learning Points:
- 📌 Multiplication before addition:
*
has higher precedence than+
- 📌 Parentheses change order: Use
()
to force different evaluation - 📌 Math before comparison: Arithmetic happens before
>
- 📌 PEMDAS rules: Python follows mathematical order of operations
💼 Practical Applications
Understanding operator precedence is crucial for writing correct expressions, especially when combining math operations, comparisons, and logical operations.
# Practical precedence examples
print("=== PRACTICAL EXAMPLES ===")
# Grade calculation with conditions
math_score = 85
english_score = 78
bonus_points = 5
# Precedence makes this work naturally
final_grade = math_score + english_score + bonus_points > 160 and math_score >= 80
print(f"Passed with honors: {final_grade}") # True
# Shopping discount calculation
price = 100
discount_percent = 20
tax_rate = 0.08
is_member = True
# Complex calculation with proper precedence
final_price = price * (1 - discount_percent / 100) * (1 + tax_rate) if is_member else price * (1 + tax_rate)
print(f"Final price: ${final_price:.2f}") # Member gets discount
# Age and permission checking
age = 17
has_parent_permission = True
is_emergency = False
# Natural precedence for complex logic
can_participate = age >= 18 or has_parent_permission and age >= 16 or is_emergency
print(f"Can participate: {can_participate}") # True
🎯 Key Takeaways
Understanding operator precedence prepares you for decision making with if statements and working with loops. This knowledge is also essential for function development and complex expressions.
Test Your Knowledge
🚀 What's Next?
Congratulations! You've completed the Python Operators section and learned about arithmetic, comparison, logical, and assignment operators, plus how they work together through precedence rules.
Next, you'll learn about Decision Making, where you'll use these operators to create intelligent programs that can make choices and respond to different conditions.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.