Python Operators
Operators are the symbols that drive the logic of any programming language. They act as the engine for calculations, data manipulation, and...
Python Operators
Section titled “Python Operators”Operators are the symbols that drive the logic of any programming language. They act as the engine for calculations, data manipulation, and decision-making.
Arithmetic Operators - Math
Section titled “Arithmetic Operators - Math”These operators perform standard mathematical calculations.
| Symbol | Name | Description | Example | Result |
|---|---|---|---|---|
| + | Addition | Adds two operands. | 5 + 3 | 8 |
| - | Subtraction | Subtracts the right operand from the left. | 10 - 2 | 8 |
| * | Multiplication | Multiplies two operands. | 4 * 2 | 8 |
| / | Division | Always returns a Float (decimal). | 10 / 2 | 5.0 |
| // | Floor Division | Division that rounds down to the nearest whole number. | 10 // 3 | 3 |
| % | Modulus | Returns the Remainder of the division. | 10 % 3 | 1 |
| ** | Exponentiation | Raises the left operand to the power of the right ($x^y$). | 2 ** 3 | 8 |
The Power of Modulus %
Section titled “The Power of Modulus %”The modulus operator is essential for logic, not just math.
-
Even/Odd Check: If number % 2 == 0, the number is Even.
-
Cyclic Indexing: If you want to loop through a list of 5 items continuously, use index % 5. The result cycles through 0, 1, 2, 3, 4, then resets to 0 automatically.
Assignment Operators
Section titled “Assignment Operators”Used to assign and update values in variables.
| Operator | Logic | Equivalent To |
|---|---|---|
| = | Assign | x = 5 |
| += | Add & Assign | x = x + 3 |
| -= | Subtract & Assign | x = x - 3 |
| *= | Multiply & Assign | x = x * 3 |
| /= | Divide & Assign | x = x / 3 |
| %= | Modulus & Assign | x = x % 3 |
The Walrus Operator :=
Section titled “The Walrus Operator :=”A special operator that allows you to assign a value to a variable inside an expression (like an if statement).
# Instead of 2 lines:# n = len(text)# if n > 10: ...
# Do it in 1 line:if (n := len(text)) > 10: print(f"Too long: {n} chars")Comparison Operators
Section titled “Comparison Operators”Used to compare two values. They always return a Boolean (True or False).
**Symbol **Name Logic==EqualTrue if values are identical.!=Not EqualTrue if values are different.>Greater Than5 > 3 is True.=Greater or Equal5 >= 5 is True.<=Less or Equal4 <= 5 is True.
Chained Comparisons
Section titled “Chained Comparisons”Python allows math-like chaining, which is cleaner than using multiple and statements.
x = 10# Clean Pythonic wayif 5 < x < 20: print("x is between 5 and 20")Logical Operators
Section titled “Logical Operators”Used to combine conditional statements. These follow Boolean logic.
| Operator | Description | Logic Rule |
|---|---|---|
| and | Returns True if BOTH statements are true. | T + T = T |
| or | Returns True if AT LEAST ONE statement is true. | T + F = T |
| not | Reverses the result. | True → False |
Short-Circuit Evaluation
Section titled “Short-Circuit Evaluation”Python evaluates logic lazily to save resources.
-
and** Short-Circuit:** If the first condition is False, Python stops immediately (result is definitely False).
-
or** Short-Circuit:** If the first condition is True, Python stops immediately (result is definitely True).
Real World Use: Preventing crashes.
# Safe Code# Python checks 'len > 0' first. If False, it never runs index[0], preventing a crash.if len(my_list) > 0 and my_list[0] == "Admin": print("Welcome Admin")Identity Operators is
Section titled “Identity Operators is”Used to compare Objects (Memory), not just Values (Data).
| Operator | Description |
|---|---|
| is | True if both variables point to the same object in memory. |
| is not | True if they point to different objects. |
The Trap: is vs ==
Section titled “The Trap: is vs ==”-
== checks Content: “Do these variables hold the same data?”
-
is checks Address: “Do these variables point to the exact same memory slot?”
list1 = [1, 2, 3]list2 = [1, 2, 3] # A copy
print(list1 == list2) # True (Data is same)print(list1 is list2) # False (They are two different lists in memory)Membership Operators in
Section titled “Membership Operators in”Used to test if a sequence (List, String, Tuple, Dict) contains a specific value.
| Operator | Description | Example |
|---|---|---|
| in | True if value is found. | “a” in “apple” |
| not in | True if value is NOT found. | “x” not in “apple” |
Bitwise Operators
Section titled “Bitwise Operators”Used to manipulate data at the binary level (bits). Critical for permissions, encryption, and low-level optimization.
| Operator | Name | Example (x=5 (0101), y=3 (0011)) | Result |
|---|---|---|---|
| & | AND | x & y (Both bits must be 1) | 0001 (1) |
| ` | ` | OR | `x |
| ^ | XOR | x ^ y (Only one bit is 1) | 0110 (6) |
| ~ | NOT | ~x (Invert all bits) | -(x+1) |
| << | Left Shift | x << 1 (Push zeros from right) | 1010 (10) |
| >> | Right Shift | x >> 1 (Push bits off right) | 0010 (2) |
Operator Precedence
Section titled “Operator Precedence”When multiple operators appear in one line, Python follows a strict hierarchy.
| Priority | Operator | Description |
|---|---|---|
| 1 (Highest) | ( ) | Parentheses (Grouping) |
| 2 | ** | Exponentiation (Power) |
| 3 | +x, -x, ~x | Unary Plus, Unary Minus, Bitwise NOT |
| 4 | *, /, //, % | Multiplication, Division, Floor Division, Modulus |
| 5 | +, - | Addition, Subtraction |
| 6 | <<, >> | Bitwise Shifts (Left/Right) |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | ` | ` |
| 10 | ==, !=, >, >=, <, <=, is, is not, in, not in | Comparisons, Identity, Membership |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 (Lowest) | or | Logical OR |
Operator Overloading - Magic Methods
Section titled “Operator Overloading - Magic Methods”You can change how operators behave for your own custom classes. For example, if you create a Wallet class, you can teach Python how to add two wallets together using +.
You define special methods (Double Underscore or “Dunder” methods):
-
add handles +
-
sub handles -
-
eq handles ==
class Wallet: def __init__(self, money): self.money = money
# Teach Python what to do when we use '+' on Wallets def __add__(self, other): return Wallet(self.money + other.money)
w1 = Wallet(50)w2 = Wallet(100)w3 = w1 + w2 # Python calls w1.__add__(w2)
print(w3.money) # Output: 150