Operators in Python
Python operators are symbols that perform operations on variables and values. Here's a breakdown of the main types:
### 1. **Arithmetic Operators**
- `+`: Addition
- `-`: Subtraction
- `*`: Multiplication
- `/`: Division (returns float)
- `%`: Modulus (remainder)
- `**`: Exponentiation (e.g., `2 ** 3 = 8`)
- `//`: Floor Division (returns integer, rounds down).
### 2. **Comparison (Relational) Operators**
- `==`: Equal to
- `!=`: Not equal to
- `>`: Greater than
- `<`: Less than
- `>=`: Greater than or equal to
- `<=`: Less than or equal to.
### 3. **Logical Operators**
- `and`: True if both operands are true.
- `or`: True if at least one operand is true.
- `not`: Inverts the boolean value (e.g., `not True → False`).
### 4. **Assignment Operators**
- `=`: Assign value (e.g., `x = 5`).
- Compound operators: `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `//=`, etc.
Example: `x += 3` is equivalent to `x = x + 3`.
### 5. **Bitwise Operators**
- `&`: Bitwise AND
- `|`: Bitwise OR
- `^`: Bitwise XOR
- `~`: Bitwise NOT (inverts bits)
- `<<`: Left shift (e.g., `5 << 1` shifts bits left by 1 → `10`).
- `>>`: Right shift (e.g., `5 >> 1` shifts bits right by 1 → `2`).
### 6. **Membership Operators**
- `in`: True if a value exists in a sequence (e.g., `2 in [1, 2, 3] → True`).
- `not in`: True if a value does not exist in a sequence.
### 7. **Identity Operators**
- `is`: True if two variables reference the same object in memory.
- `is not`: True if two variables reference different objects.
Example:
```python
a = [1, 2]
b = a
c = [1, 2]
print(a is b) # True (same object)
print(a is c) # False (different objects, even if values match)
```
### 8. **Ternary Conditional Operator**
- Syntax: `x = a if condition else b`.
Example:
```python
age = 20
status = "Adult" if age >= 18 else "Minor" # "Adult"
```
### 9. **Walrus Operator (:=)**
- Assignment expression (Python 3.8+). Assigns values as part of an expression.
Example:
```python
if (n := len([1, 2, 3])) > 2:
print(n) # Output: 3
```
### Operator Precedence (Highest to Lowest)
1. Parentheses `()`
2. Exponentiation `**`
3. Unary operators (`+x`, `-x`, `~x`)
4. Multiplication/Division: `*`, `/`, `//`, `%`
5. Addition/Subtraction: `+`, `-`
6. Bitwise shifts: `<<`, `>>`
7. Bitwise AND `&`
8. Bitwise XOR `^`
9. Bitwise OR `|`
10. Comparison: `==`, `!=`, `>`, `<`, `>=`, `<=`
11. Identity: `is`, `is not`
12. Membership: `in`, `not in`
13. Logical NOT `not`
14. Logical AND `and`
15. Logical OR `or`
16. Assignment operators: `=`, `+=`, `-=`, etc.
### Example Usage
```python
# Arithmetic
print(10 // 3) # 3 (floor division)
print(2 ** 3) # 8 (exponentiation)
# Logical
print(True and False) # False
# Membership
print("a" in "apple") # True
# Identity
a = 5
b = 5
print(a is b) # True (small integers are interned in Python)
```
Understanding operators and their precedence is key to writing efficient and bug-free Python code. Use parentheses to clarify complex expressions!
Comments
Post a Comment