Python Operators — Notes
1. What are Operators?
- Operators are special symbols or keywords that perform operations on variables and values.
Example:
x = 5 + 3 # '+' is an addition operator
2. Types of Operators in Python
a) Arithmetic Operators
Used for mathematical operations:
| Operator | Description | Example |
|---|---|---|
+ |
Addition | x + y |
- |
Subtraction | x - y |
* |
Multiplication | x * y |
/ |
Division | x / y |
% |
Modulus (remainder) | x % y |
** |
Exponentiation | x ** y |
// |
Floor Division | x // y |
Example:
a = 10
b = 3
print(a + b) # 13
print(a ** b) # 1000
b) Comparison (Relational) Operators
Used to compare values — return True or False.
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Example:
x = 5
print(x > 3) # True
c) Assignment Operators
Used to assign values to variables:
| Operator | Example | Equivalent to |
|---|---|---|
= |
x = 5 |
Assigns 5 to x |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
**= |
x **= 3 |
x = x ** 3 |
//= |
x //= 3 |
x = x // 3 |
d) Logical Operators
Used to combine conditional statements:
| Operator | Meaning | Example |
|---|---|---|
and |
True if both are True | x > 3 and y < 10 |
or |
True if at least one is True | x > 3 or y < 10 |
not |
True if condition is False | not(x > 3) |
e) Bitwise Operators
Operate on binary numbers:
| Operator | Meaning | |
|---|---|---|
& |
AND | |
| ` | ` | OR |
^ |
XOR | |
~ |
NOT | |
<< |
Left shift | |
>> |
Right shift |
Example:
a = 5 # 0101
b = 3 # 0011
print(a & b) # 1 (0001)
f) Membership Operators
Check if a value is in a sequence:
| Operator | Meaning |
|---|---|
in |
True if found |
not in |
True if not found |
Example:
fruits = ["apple", "banana"]
print("apple" in fruits) # True
print("cherry" not in fruits) # True
g) Identity Operators
Check if two variables refer to the same object:
| Operator | Meaning |
|---|---|
is |
True if same object |
is not |
True if different objects |
Example:
x = [1, 2]
y = x
z = [1, 2]
print(x is y) # True
print(x is z) # False