Operator precedence in Python is a set of rules that dictate the order in which the operators are evaluated in an expression. These rules help to avoid ambiguity in the evaluation of expressions, and they ensure that the expressions are evaluated in a predictable and consistent way.
In Python, the order of precedence is as follows (from highest to lowest):
If an expression contains multiple operators, the operator with the highest precedence is evaluated first. If two operators have the same precedence, then they are evaluated from left to right.
It’s important to keep these rules in mind when writing complex expressions in Python to ensure that they are evaluated correctly.
Here are some examples to illustrate operator precedence in Python:
Example 1:
result = 2 + 3 * 4
print(result)
Output: 14
Explanation: In this example, the multiplication operator has a higher precedence than the addition operator. So, 3 * 4 is evaluated first, and the result (12) is added to 2, giving us 14.
Example 2:
result = (2 + 3) * 4
print(result)
Output: 20
Explanation: In this example, the parentheses have the highest precedence, so (2 + 3) is evaluated first, giving us 5. Then, the multiplication operator is evaluated, giving us the final result of 20.
Example 3:
result = 3 ** 2 + 4 ** 2
print(result)
Output: 25
Explanation: In this example, both exponentiation operators have the same precedence, so they are evaluated from left to right. So, 3 ** 2 is evaluated first, giving us 9, and then 4 ** 2 is evaluated, giving us 16. Finally, the addition operator is evaluated, giving us the final result of 25.
Here are some more uses and examples of operator precedence in Python:
Example 1:
result = 5 * 2 + 10 / 2
print(result)
Output: 17.0
Explanation: In this example, the multiplication operator has higher precedence than the division operator, so 5 * 2 is evaluated first, giving us 10. Then, the division operator is evaluated, giving us 5. Finally, the addition operator is evaluated, giving us the final result of 17.0.
Example :
result = 2 ** 3 ** 2
print(result)
Output: 512
Explanation: In this example, the exponentiation operator has right-to-left associativity. So, 3 ** 2 is evaluated first, giving us 9. Then, 2 ** 9 is evaluated, giving us the final result of 512.
Example :
result = 10 % 3 * 2 – 5
print(result)
Output: 0
Explanation: In this example, the modulo operator has higher precedence than the multiplication and subtraction operators.
So, 10 % 3 is evaluated first, giving us 1. Then, 1 * 2 is evaluated, giving us 2. Finally, the subtraction operator is evaluated, giving us the final result of 0.
Example 4:
result = not True and False or not False
print(result)