Operator Precedence in Python
Understanding Precedence
What is Precedence?
In Python, precedence refers to the order in which operations are performed in an expression. Some
operations are done before others unless parentheses are used to override this.
Example Without Precedence:
result = 3 + 4 * 2
This equals 11 because multiplication has higher precedence than addition.
Operator Precedence (From Highest to Lowest):
1. () : Parentheses
2. ** : Exponentiation
3. +x, -x, ~x : Unary plus, minus, bitwise NOT
4. *, /, //, % : Multiplication, division, floor division, modulo
5. +, - : Addition and subtraction
6. <<, >> : Bitwise shift
7. & : Bitwise AND
8. ^ : Bitwise XOR
9. | : Bitwise OR
10. Comparisons : ==, !=, >, <, >=, <=, is, in, not in, is not
11. not : Logical NOT
12. and : Logical AND
13. or : Logical OR
14. =, +=, -= etc.: Assignment
Example with Multiple Operators:
x = 5 + 2 * 3 ** 2
Operator Precedence in Python
Steps:
3 ** 2 = 9
2 * 9 = 18
5 + 18 = 23
Use parentheses to control the order explicitly:
x = (5 + 2) * (3 ** 2) # = 7 * 9 = 63