Operator Precedence and Associativity
Following our exploration of Operators: Logical and Bitwise Operators, this article dives into the rules that govern the order in which operators are evaluated: operator precedence and associativity.
📚 Prerequisites
A basic understanding of Python operators.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ What operator precedence is and why it's important.
- ✅ The order of precedence for common Python operators.
- ✅ What operator associativity is and how it works.
- ✅ How to use parentheses to control the order of evaluation.
🧠 Section 1: Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression. For example, multiplication has a higher precedence than addition.
result = 10 + 5 * 2 # 5 * 2 is evaluated first
print(result) # Output: 20
You can use parentheses to override the default precedence:
result = (10 + 5) * 2 # 10 + 5 is evaluated first
print(result) # Output: 30
💻 Section 2: Python Operator Precedence
Here is a table of Python operators, from highest precedence to lowest:
| Precedence | Operator | Description |
|---|---|---|
| Highest | () | Parentheses |
** | Exponentiation | |
*, /, //, % | Multiplication, Division, Floor Division, Modulus | |
+, - | Addition, Subtraction | |
<<, >> | Bitwise shifts | |
& | Bitwise AND | |
^ | Bitwise XOR | |
| ` | ` | |
==, !=, >, >=, <, <= | Comparisons | |
is, is not | Identity operators | |
in, not in | Membership operators | |
not | Logical NOT | |
and | Logical AND | |
| Lowest | or | Logical OR |
🛠️ Section 3: Operator Associativity
When an expression has multiple operators with the same precedence, associativity determines the order of evaluation. Most Python operators are left-associative, meaning they are evaluated from left to right.
result = 100 / 10 * 2 # 100 / 10 is evaluated first
print(result) # Output: 20.0
The main exception is the exponentiation operator (**), which is right-associative:
result = 2 ** 3 ** 2 # 3 ** 2 is evaluated first
print(result) # Output: 512 (2 ** 9)
💡 Conclusion & Key Takeaways
You've now learned about operator precedence and associativity, the rules that govern the order of operations in Python.
Let's summarize the key takeaways:
- Precedence: The order in which operators are evaluated.
- Associativity: The order in which operators of the same precedence are evaluated.
- Parentheses: Use parentheses to explicitly control the order of evaluation.
Challenge Yourself:
Predict the output of the following expression, and then verify your answer in a Python interpreter: 5 * 2 ** 3 + 4 / 2
➡️ Next Steps
In the next article, we'll learn about "Common Built-in Functions: len(), type(), range(), etc.".
Happy coding!
Glossary (Python Terms)
- Operator Precedence: The order in which operators are evaluated in an expression.
- Operator Associativity: The order in which operators of the same precedence are evaluated.