The combination of values, variables, operators and function calls is termed as an expression. Python interpreter can evaluate a valid expression.
>>> 5 - 7
>>> 5 - 7
Here 5 - 7 is an expression. There can be more than one operator in an expression.
5 - 7
To evaluate these type of expressions there is a rule of precedence in Python. It guides the order in which operation are carried out.
For example, multiplication has higher precedence than subtraction.
# Multiplication has higher precedence
# than subtraction
# Output: 2
10 - 4 * 2
But we can change this order using parentheses () as it has higher precedence.
# Parentheses () has higher precendence
# Output: 12
(10 - 4) * 2
The operator precedence in Python are listed in the following table. It is in descending order, upper group has higher precedence than the lower ones.
We can see in the above table that more than one operator exists in the same group. These operators have the same precedence.
When two operators have the same precedence, associativity helps to determine which the order of operations.
Associativity is the order in which an expression is evaluated that has multiple operator of the same precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, left one is evaluates first.
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
Exponent operator ** has right-to-left associativity in Python.
# Right-left associativity of ** exponent operator
# Output: 512
print(2 ** 3 ** 2)
# Shows the right-left associativity
# of **
# Output: 64
print((2 ** 3) ** 2)
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
2 ** 3 ** 2
2 ** (3 ** 2)
Some operators like assignment operators and comparison operators do not have associativity in Python. There are separate rules for sequences of this kind of operator and cannot be expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x < y and y < z, and is evaluates from left-to-right.
x < y < z
(x < y) < z
x < (y < z)
x < y and y < z
Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += z will result into error.
x = y = z
x = y += z
# Initialize x, y, z
x = 1, y = 1, z = 1
# Expression is invalid
# (Non-associative operators)
# SyntaxError: invalid syntax
x = y += 2