In Python, operators have a specific order of precedence, which determines how
expressions are evaluated. Operators with higher precedence are evaluated before
operators with lower precedence. Here's the order of precedence from highest to lowest:
1. **Parentheses**: `()`
Used to override the default precedence and explicitly specify the order of evaluation.
2. **Exponentiation**: `**`
Evaluates from right to left.
3. **Unary Operators**: `+`, `-`, `~`
Unary plus, minus (negation), and bitwise NOT.
4. **Multiplication, Division, Modulus, Floor Division**: `*`, `/`, `%`, `//`
5. **Addition, Subtraction**: `+`, `-`
6. **Bitwise Shift Operators**: `<<`, `>>`
Left and right shifts.
7. **Bitwise AND**: `&`
8. **Bitwise XOR**: `^`
9. **Bitwise OR**: `|`
10. **Comparison Operators**: `==`, `!=`, `>`, `>=`, `<`, `<=`, `is`, `is not`, `in`, `not in`
11. **Boolean NOT**: `not`
Negates a Boolean expression.
12. **Boolean AND**: `and`
13. **Boolean OR**: `or`
14. **Assignment Operators**: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `//=`, `**=`, `&=`, `|=`, `^=`,
`>>=`, `<<=`
15. **Lambda Operator**: `lambda`
Used to define anonymous functions.
examples that demonstrate the precedence of operators in Python:
### 1. **Exponentiation vs Multiplication**
```python
result = 2 ** 3 * 2 # Exponentiation happens first
# Equivalent to: (2 ** 3) * 2
print(result) # Output: 16
```
### 2. **Multiplication vs Addition**
```python
result = 2 + 3 * 4 # Multiplication happens before addition
# Equivalent to: 2 + (3 * 4)
print(result) # Output: 14
```
### 3. **Parentheses Override Precedence**
```python
result = (2 + 3) * 4 # Parentheses change the order
print(result) # Output: 20
```
### 4. **Unary Minus vs Exponentiation**
```python
result = -3 ** 2 # Exponentiation happens before negation
# Equivalent to: -(3 ** 2)
print(result) # Output: -9
```
### 5. **Division vs Subtraction**
```python
result = 10 - 2 / 2 # Division happens before subtraction
# Equivalent to: 10 - (2 / 2)
print(result) # Output: 9.0
```
### 6. **Comparison vs Addition**
```python
result = 3 + 2 > 4 # Addition happens before comparison
# Equivalent to: (3 + 2) > 4
print(result) # Output: True
```
### 7. **Logical NOT vs AND**
```python
result = not True and False # NOT happens before AND
# Equivalent to: (not True) and False
print(result) # Output: False
```
### 8. **Bitwise AND vs OR**
```python
result = 2 | 3 & 1 # Bitwise AND happens before OR
# Equivalent to: 2 | (3 & 1)
print(result) # Output: 2
```
### 9. **Assignment and Arithmetic**
```python
x=5
x += 3 * 2 # Multiplication happens before assignment addition
# Equivalent to: x += (3 * 2)
print(x) # Output: 11
```
These examples illustrate how Python evaluates expressions based on operator
precedence, helping you understand which operations are performed first.