Operator precedence defines the order in which operations are performed when evaluating an expression. In Python, certain operators are evaluated before others. For example, in the expression 1 + 2 * 3
, multiplication (*
) has higher precedence than addition (+
), so 2 * 3
is evaluated first, followed by 1 + 6
, resulting in 7
.
Understanding operator precedence is essential for accurately interpreting and writing Python code. It dictates how complex expressions are evaluated and helps prevent logical errors.
-
Parentheses
(expression)
-
Exponentiation
**
-
Unary Plus, Unary Minus, Bitwise NOT
+x, -x, ~x
-
Multiplication, Division, Modulus
*, /, //, %
-
Addition, Subtraction
+, -
-
Bitwise Shift
<<, >>
-
Bitwise AND
&
-
Bitwise XOR
^
-
Bitwise OR
|
-
Comparison Operators
<, <=, >, >=, ==, !=
-
Identity Operators
is, is not
-
Membership Operators
in, not in
-
Logical NOT
not
-
Logical AND
and
-
Logical OR
or
-
Conditional Operator
expression1 if condition else expression2
-
Assignment Operators
=, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, <<=, >>=
result = not 5 > 3 # Equivalent to not (5 > 3)
result = not 5 + 3 # Equivalent to not (5 + 3)
result = not True or False # Equivalent to (not True) or False
result = not True and False # Equivalent to (not True) and False
result = not not True # Equivalent to not (not True)
To make the precedence explicit, use parentheses:
result = (not True) and (5 > 3)
This cheat sheet aims to provide a quick reference for understanding Python's operator precedence. When in doubt, use parentheses to clarify the order of operations.