Table of Contents#
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Identity Operators
- Membership Operators
- Operator Precedence
- Advanced Topics
- Conclusion
- References
1. Arithmetic Operators#
Arithmetic operators perform basic mathematical operations. Python supports all standard arithmetic operations, plus a few unique ones like floor division and modulus.
| Operator | Name | Description | Example | Output |
|---|---|---|---|---|
+ | Addition | Adds two operands | 5 + 3 | 8 |
- | Subtraction | Subtracts the right operand from the left | 10 - 4 | 6 |
* | Multiplication | Multiplies two operands | 6 * 7 | 42 |
/ | Division | Divides the left operand by the right (returns float) | 15 / 4 | 3.75 |
// | Floor Division | Divides and returns the largest integer ≤ result | 15 // 4 | 3 |
% | Modulus | Returns the remainder of division | 15 % 4 | 3 |
** | Exponentiation | Raises the left operand to the power of the right | 2** 3 | 8 |
Key Examples:#
-
Division vs. Floor Division:
Regular division (/) always returns a float, even if the result is an integer:print(10 / 2) # Output: 5.0Floor division (
//) truncates the decimal part and returns an integer:print(10 // 3) # Output: 3 (since 3 * 3 = 9 ≤ 10) print(-10 // 3) # Output: -4 (Python rounds down to the nearest integer) -
Modulus with Negative Numbers:
The result ofa % bhas the same sign asb(the divisor):print(15 % 4) # 15 = 3*4 + 3 → Output: 3 (same sign as 4) print(-15 % 4) # -15 = (-4)*4 + 1 → Output: 1 (same sign as 4) print(15 % -4) # 15 = (-4)*-4 + (-1) → Output: -1 (same sign as -4) -
Exponentiation:
Use**for powers, orpow()for larger exponents:print(2** 5) # Output: 32 print(pow(3, 4)) # Output: 81 (equivalent to 3**4)
2. Assignment Operators#
Assignment operators assign values to variables. The basic operator is =, but Python also supports compound assignment operators that combine an operation with assignment (e.g., +=, -=).
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x - 2 |
*= | x *= 4 | x = x * 4 |
/= | x /= 2 | x = x / 2 |
//= | x //= 3 | x = x // 3 |
%= | x %= 5 | x = x % 5 |
**= | x **= 3 | x = x ** 3 |
Example:#
x = 10
x += 5 # x = x + 5 → x becomes 15
x *= 2 # x = x * 2 → x becomes 30
print(x) # Output: 30 3. Comparison Operators#
Comparison operators compare two values and return a Boolean result (True or False). They are critical for control flow (e.g., if statements, loops).
| Operator | Name | Description | Example | Output |
|---|---|---|---|---|
== | Equal to | Checks if values are equal | 5 == 5 | True |
!= | Not equal to | Checks if values are not equal | 5 != 3 | True |
> | Greater than | Checks if left > right | 7 > 3 | True |
< | Less than | Checks if left < right | 2 < 5 | True |
>= | Greater than or equal | Checks if left ≥ right | 4 >= 4 | True |
<= | Less than or equal | Checks if left ≤ right | 3 <= 1 | False |
Key Notes:#
-
String Comparison: Strings are compared lexicographically (based on Unicode values):
print("apple" < "banana") # True ("a" comes before "b") print("Apple" < "apple") # True ("A" has a lower Unicode value than "a") -
None Comparison: Use
is(not==) to check forNone(see Identity Operators):x = None print(x == None) # Works but not recommended print(x is None) # Preferred (more explicit)
4. Logical Operators#
Logical operators combine Boolean expressions to form complex conditions. Python supports and, or, and not.
| Operator | Name | Description |
|---|---|---|
and | Logical AND | Returns True only if both operands are True |
or | Logical OR | Returns True if at least one operand is True |
not | Logical NOT | Inverts the Boolean value of the operand |
Short-Circuit Evaluation:#
Python uses short-circuiting to optimize logical operations:
and: Stops evaluating once aFalseoperand is found (returns the first falsy value).or: Stops evaluating once aTrueoperand is found (returns the first truthy value).
Examples:#
# and: Returns first falsy value (0 is falsy)
print(0 and 5) # Output: 0
# or: Returns first truthy value (5 is truthy)
print(0 or 5) # Output: 5
# not: Inverts the value
print(not True) # Output: False
print(not 0) # Output: True (0 is falsy, so not 0 is True) Truthy vs. Falsy Values:#
In Python, values are considered "truthy" (evaluate to True) unless they are:
FalseNone0(or0.0,0j)- Empty sequences (
"",[],(),{}) - Empty collections (
set(),dict())
5. Bitwise Operators#
Bitwise operators manipulate integers at the bit level (binary representation). They are used in low-level programming, cryptography, and performance-critical applications.
| Operator | Name | Description | Example (Binary) | Decimal Output |
|---|---|---|---|---|
& | Bitwise AND | Sets each bit to 1 if both bits are 1 | 5 (101) & 3 (011) → 001 | 1 |
| ` | ` | Bitwise OR | Sets each bit to 1 if at least one bit is 1 | `5 (101) |
^ | Bitwise XOR | Sets each bit to 1 if exactly one bit is 1 | 5 (101) ^ 3 (011) → 110 | 6 |
~ | Bitwise NOT | Inverts all bits (two’s complement: ~x = -x - 1) | ~5 (00000101) → 11111010 | -6 |
<< | Left Shift | Shifts bits left by n positions (equivalent to x * 2^n) | 5 << 2 → 10100 (20) | 20 |
>> | Right Shift | Shifts bits right by n positions (equivalent to x // 2^n) | 20 >> 2 → 101 (5) | 5 |
Example:#
a = 10 # Binary: 1010
b = 4 # Binary: 0100
print(a & b) # 0000 → 0
print(a | b) # 1110 → 14
print(a ^ b) # 1110 → 14? Wait, 1010 ^ 0100 = 1110 (14). Correct.
print(~a) # -11 (since ~10 = -10 -1 = -11)
print(a << 1) # 10100 (20)
print(a >> 2) # 10 (2) 6. Identity Operators#
Identity operators check if two variables point to the same object (i.e., share the same memory address). They are is and is not.
| Operator | Description | Example | Output |
|---|---|---|---|
is | Returns True if both variables are the same object | x is y | True/False |
is not | Returns True if variables are different objects | x is not y | True/False |
Key Difference: == vs. is#
==checks if values are equal.ischecks if objects are identical (same memory address).
Example:#
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x == y) # True (values are equal)
print(x is y) # False (different objects)
print(x is z) # True (same object) Note: Small Integer Interning#
Python "interns" small integers (-5 to 256) to save memory, so they reuse the same object:
a = 10
b = 10
print(a is b) # True (same object)
c = 257
d = 257
print(c is d) # False (different objects in some Python implementations) 7. Membership Operators#
Membership operators check if a value is present in a sequence (e.g., list, string, tuple) or collection (e.g., set, dictionary). They are in and not in.
| Operator | Description | Example | Output |
|---|---|---|---|
in | Returns True if value is in the sequence | 5 in [1, 2, 5] | True |
not in | Returns True if value is not in the sequence | 5 not in [1, 2, 3] | True |
Examples:#
# Lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
# Strings (checks for substring)
text = "Hello, World!"
print("World" in text) # True
# Dictionaries (checks for keys, not values)
person = {"name": "Alice", "age": 30}
print("name" in person) # True
print("Alice" in person) # False (checks keys, not values) 8. Operator Precedence#
When an expression has multiple operators, Python follows a precedence order to determine which operations to perform first. Use parentheses () to override precedence.
| Precedence | Operators |
|---|---|
| Highest | () (parentheses) |
** (exponentiation) | |
~, +, - (unary ops) | |
*, /, //, % | |
+, - (binary ops) | |
<<, >> (bitwise shifts) | |
& (bitwise AND) | |
^ (bitwise XOR) | |
| ` | |
==, !=, >, <, >=, <= | |
is, is not | |
in, not in | |
not | |
and | |
| Lowest | or |
Example:#
# Without parentheses: 3 * 2 is evaluated first
print(2 + 3 * 2) # 2 + 6 = 8
# With parentheses: 2 + 3 is evaluated first
print((2 + 3) * 2) # 5 * 2 = 10 9. Advanced Topics#
Chained Comparisons#
Python allows chaining multiple comparisons for readability:
x = 5
print(1 < x < 10) # Equivalent to (1 < x) and (x < 10) → True
print(10 < x < 20) # False Custom Operators (Operator Overloading)#
You can define custom behavior for operators in classes by overriding special methods (e.g., __add__ for +, __eq__ for ==).
Example: A Vector class with overloaded +:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3) # Output: Vector(6, 8) 10. Conclusion#
Operators are the backbone of Python programming, enabling everything from simple calculations to complex logic. By mastering arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators, you’ll be able to write more expressive and efficient code. Remember operator precedence to avoid bugs, and experiment with custom operators to extend Python’s functionality.
Practice with real-world examples (e.g., calculating discounts, validating user input, or processing binary data) to solidify your understanding!