Python Operator Precedence

Operator precedence in Python determines the order in which different operators are evaluated in an expression. It ensures that mathematical and logical expressions are computed correctly. Python follows the standard operator precedence rules, where some operators are evaluated before others. Operators with higher precedence are evaluated first.

Operator Precedence in Python:

1. Parentheses () - Highest precedence

2. Exponentiation **

3. Unary positive +, unary negation -

4. Multiplication *, Division /, Floor Division //, Modulus %

5. Addition +, Subtraction -

6. Bitwise Left Shift <<, Bitwise Right Shift >>

7. Bitwise AND &

8. Bitwise XOR ^

9. Bitwise OR |

10. Comparison operators: <, <=, >, >=, !=, ==

11. Logical NOT not

12. Logical AND and

13. Logical OR or

Let's illustrate these rules with some examples:

        
# Example 1: Multiplication and Addition
result = 2 + 3 * 4
# Here, multiplication has a higher precedence, so 3 * 4 is evaluated first.
# Then, the addition is performed, resulting in 14.

# Example 2: Exponentiation and Parentheses
result = (2 + 3) ** 2
# The parentheses have the highest precedence, so 2 + 3 is calculated first,
# and then the result is squared, resulting in 25.

# Example 3: Bitwise and Logical Operators
a = 5
b = 3
c = 7
result = a & b < c
# First, bitwise AND (a & b) is evaluated, resulting in 1 (binary 001 & 011 = 001).
# Then, the comparison operator < is evaluated, resulting in True (1 < 7).

# Example 4: Mix of Operators
x = 10
y = 20
z = 5
result = x + y * z ** 2 / (x - z)
# Following the precedence rules:
# 1. z ** 2 is evaluated first, resulting in 25.
# 2. Then, y * 25 is calculated, resulting in 500.
# 3. Next, (x - z) is evaluated, resulting in 5.
# 4. Finally, x + 500 / 5 is computed, resulting in 110.

# Example 5: Logical Operators and Parentheses
a = True
b = False
c = True
result = (a and b) or (not c)
# In this example, the parentheses ensure that 'not c' is evaluated first,
# resulting in False. Then, 'a and b' is evaluated as False and 'False or False' is also False.
# So, the result is False.