Need for Role of Precedence:
In Python, operator precedence determines the order in which operations are performed in an expression. Without clear rules, complex expressions could be interpreted in multiple ways, leading to unexpected results or errors.
To avoid this, Python follows a specific set of precedence rules—just like how grammar is important in language—to ensure expressions are evaluated correctly.
Rules of Precedence in Python (From Highest to Lowest):
Precedence | Operator(s) | Description |
---|---|---|
Highest | ** | Exponentiation |
* , / , // , % | Multiplication, Division, Floor Division, Modulus | |
Lowest | + , - | Addition and Subtraction |
- Operators with higher precedence are evaluated before operators with lower precedence.
- Left to right associativity is followed for most operators, except for
**
which is right-to-left. - Parentheses
()
can be used to override the default precedence.
Examples:
2 + 3 * 6
20 # Multiplication (*) is done before addition (+)(2 + 3) * 6
30 # Parentheses alter the order, so addition is done first2 ** 8
256 # Exponentiation has the highest precedence23 / 7
3.2857142857142856 # Normal division23 // 7
3 # Floor division gives integer result23 % 7
2 # Modulus returns the remainder(5 – 1) * ((7 + 1) / (3 – 1))
16.0 # Combined usage of all operators and parentheses
Python will keep evaluating parts of the expression until it becomes a single value:
