Python Operators ➕
Types of Operators
Operators are used to perform operations on variables and values. Python divides the operators into the following groups:
➕ Arithmetic Operators
| Operator | Name | Example |
|---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
** | Exponentiation | x ** y |
// | Floor division | x // y |
🎯 Real-World Application: Modulus (%)
The modulus operator is used to find the remainder. It's super useful for checking if a number is even or odd!
number = 10
if number % 2 == 0:
print("Even")
else:
print("Odd")🧠 Logical Operators
Logical operators are used to combine conditional statements:
x = 5
print(x > 3 and x < 10) # True (Both conditions are true)
print(x > 3 or x < 4) # True (At least one condition is true)
print(not(x > 3 and x < 10)) # False (Reverse the result)🆔 Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True (z is the same object as x)
print(x is y) # False (x and y are different objects, even if they have the same content)
print(x == y) # True (x and y are equal)⚠️ Watch Out: "is" vs "=="
== checks if the values are equal.is checks if they are the same object in memory.
Always use == for comparing values like strings or numbers.
🔍 Membership Operators
Membership operators are used to test if a sequence is presented in an object:
x = ["apple", "banana"]
print("banana" in x) # True
print("pineapple" not in x) # True⚙️ Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
| Operator | Name | Description |
|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if one of two bits is 1 |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
~ | NOT | Inverts all the bits |
<< | Zero fill left shift | Shift left by pushing zeros in from the right |
>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left |
✨ Pro Tip: The Walrus Operator (:=)
Introduced in Python 3.8, the walrus operator allows you to assign values to variables as part of an expression.
# Without walrus operator
n = len(a)
if n > 10:
print(f"List is too long ({n} elements)")
# With walrus operator
if (n := len(a)) > 10:
print(f"List is too long ({n} elements)")