In Python, the operator precedence determines the order in which operators are evaluated in an expression. Ensuring that your source code performs the intended calculations is crucial. Misunderstanding the operator precedence can lead to subtle bugs and unexpected behaviour in your programs. This article explained everything about the operator Precedence in Python and its examples.
Operators Precedence in Python
The Operator’s precedence in Python determines the order in which different operators in an expression are evaluated. Operators with higher precedence are evaluated before those with lower precedence. This hierarchy of precedence ensures that expressions are evaluated consistently.
The following program demonstrates the Python Operator Precedence:
Program
def demonstrate_precedence():
arithmetic_result = 2 + 3 * 4
print(f"Example 1: 2 + 3 * 4 = {arithmetic_result}")
exponentiation_result = 2 ** 3 * 4
print(f"Example 2: 2 ** 3 * 4 = {exponentiation_result}")
parentheses_result = (2 + 3) * 4
print(f"Example 3: (2 + 3) * 4 = {parentheses_result}")
unary_result = -2 ** 3
print(f"Example 4: -2 ** 3 = {unary_result}")
logical_result = True or False and False
print(f"Example 5: True or False and False = {logical_result}")
comparison_result = 5 < 10 == 10
print(f"Example 6: 5 < 10 == 10 = {comparison_result}")
bitwise_result = 4 & 3 | 2
print(f"Example 7: 4 & 3 | 2 = {bitwise_result}")
x = 5
conditional_result = x if x > 0 else -x
print(f"Example 8: x if x > 0 else -x = {conditional_result}")
if __name__ == "__main__":
demonstrate_precedence()
Output
Example 1: 2 + 3 * 4 = 14
Example 2: 2 ** 3 * 4 = 32
Example 3: (2 + 3) * 4 = 20
Example 4: -2 ** 3 = -8
Example 5: True or False and False = True
Example 6: 5 < 10 == 10 = True
Example 7: 4 & 3 | 2 = 2
Example 8: x if x > 0 else -x = 5

POSTGRADUATE PROGRAM IN
Multi Cloud Architecture & DevOps
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.
Python Operators Precedence Table
The following table describes the Operator’s Precedence:
| Operators | Description |
| () | Parentheses for grouping |
| ‘**” | Exponentiation (right associative) |
| ‘+x’, ‘-x’ , ‘~x’ | Unary plus, unary minus, bitwise NOT |
| ‘*’ , ‘/’, ‘%’, ‘//’ | Multiplication, division, modulo, floor division |
| ‘+’, ‘-’ | Addition, Subtraction |
| ‘<<’, “>>” | Bitwise left shift, bitwise right shift |
| ‘&’ | Bitwise AND |
| ‘^’ | Bitwise XOR |
| ‘ | ‘ |
| ‘==”, ‘!=’ ,’ >’ ‘<’ , ‘>=’ , ‘<=’ | Equality, inequality, comparison |
| ‘not’ | Logical Not |
| ‘or’ | Logical OR |
| ‘if-else’ | Conditional expression (ternary operator) |
| ‘=’, ‘+=’, ‘-=’ , ‘*=’ , ‘/=’, etc | Assignment operators and augmented assignments |
| ‘,’ | The comma (used for tuple packing and function arguments) |
| ‘:’ | It is used in slices, annotations, and dictionary key-value pairs |
Python Operators Precedence Rule – PEMDAS
Python operator precedence follows the PEMDAS rule for arithmetic expression. The precedence of operators is listed below in a high-to-low manner.
- P – Parentheses
- E – Exponentiation
- M – Multiplication
- D – Division
- A – Addition
- S – Subtraction
Associativity Rule
In Python, All the operators follow the left-to-right pattern except the exponentiation (**) operator. In other words, the evaluation will proceed from left to right.
For Example : (99 + 55 – 9 /3 * 5)
In this example, the multiplication and division operators have equal precedence. However, they are evaluated according to the left-to-right associativity.
The following program demonstrates the Associativity Rule :
Program
a = (24 ** 2 // 5 % 34 / 30 * 8)
b = (9 << 10 >> 5)
c = (3 ** 2 ** 2)
print (a)
print (b)
print (c)
<strong>Output</strong>
3.466666666666667
288
81

82.9%
of professionals don't believe their degree can help them get ahead at work.
Comparison Operators
All the comparison operations in Python, such as <,>,==, >=, <=, != have the same priority. The lower arithmetic, shifting and bitwise operations. Unlike in C, Python always follows the conventional mathematical interpretation for expressions like a < b < c.
The following program demonstrates the comparison Operation in Java:
Program
a = 10
b = 20
print("{a} > {b}: {a > b}")
print("{a} < {b}: {a < b}")
print("{a} == {b}: {a == b}")
print("{a} != {b}: {a != b}")
print("{a} >= {b}: {a >= b}")
print("{a} <= {b}: {a <= b}")
x = "Harry"
y = "Potter"
print('"{x}" > "{y}": {x > y}')
print('"{x}" < "{y}": {x < y}')<strong> </strong>
Output
{a} > {b}: {a > b}
{a} < {b}: {a < b}
{a} == {b}: {a == b}
{a} != {b}: {a != b}
{a} >= {b}: {a >= b}
{a} <= {b}: {a <= b}
"{x}" > "{y}": {x > y}
"{x}" < "{y}": {x < y}
Examples of Comparison Operators
In this section, we will see some operator precedence in Python to get a good idea of how these things work internally.
Precedence of Operators
The following program demonstrates the Precedence of Operators:
Program
a = (105+ 12 * 35% 30 / 2)
b = (3 ^ 2 << 9 + 48 // 24)
print (a)
print (b)
Output
105.0
4099
Also Visit: Python Tutorial for Beginners
Conclusion
In Python, operator precedence refers to the order in which Python evaluates or performs operators in an expression. It defines how more than one operator is applied within proximity. Keeping things clear and accurate in the code is always better from right to left.
To be certain of the clarity and correctness of source code, parentheses should be used explicitly to define the intended order of operations in all situations where there might be a mixing of operators with different precedence levels.
We know the rules of precedence and apply them by writing expressions evaluated as intended, which may then be used to maintain readable and reliable source code.
What is operator precedence?
What is associativity?
What is the precedence of comparison operators?
How does Python handle the precedence of ‘is’ and ‘is not’ operators?
How does precedence affect the use of the ‘del’ keyword?
Updated on September 2, 2024
