What is the order of precedence of operators in Python?
Overview
Operator precedence in Python simply refers to the order of operations. Operators are used to perform operations on variables and values.
Assignment operators
Common assignment operators in Python include:
- Assign
= - Add AND
+= - Subtract AND
-= - Multiply AND
*= - Divide AND
/= - Modulo AND
%= - Exponent AND
**=
Order of operations
Since these operators are not associative, there is no order of operations for them. They are always performed or declared exclusively.
Example
# using the assigm operatorx = 6y = 2# to generate the Add AND operator i.e x + y = 8x += yprint(x)# to generate the subtract AND operator i.e x - y = 8 - 2 = 6x -= yprint(x)# to generate the multiply AND ooperator i.e x * y = 6 * 2 = 12x *= yprint(x)# to generate the divide AND operator i.e x / 2 = 12 / 2 = 6x /= yprint(x)# to generate the modulo AND operator 1.e x %= 2 = 6 % 2 = 0x %= yprint(x)# to generate the exponent AND operator 1.e x **= y = 0x **= yprint(x)
Explanation
-
Lines 1–2: We declare and assign values to two variables,
xandy. -
Line 5: We demonstrate the Add AND operator.
-
Line 8: We demonstrate the subtract AND operator.
-
Line 11: We demonstrate the multiply AND operator.
-
Line 14: We demonstrate the divide AND operator.
-
Line 17: We demonstrate the modulo AND operator.
-
Line 20: We demonstrate the exponent AND operator.