Python Operators
🐍 Python Operators
Operators in Python are used to perform operations on variables and values.
Python has 7 types of operators:
Arithmetic Operators
Assignment Operators
Comparison (Relational) Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
1️⃣ Arithmetic Operators
Used for mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 10 + 5 → 15 |
- | Subtraction | 10 - 5 → 5 |
* | Multiplication | 10 * 5 → 50 |
/ | Division | 10 / 5 → 2.0 |
% | Modulus (remainder) | 10 % 3 → 1 |
// | Floor Division | 10 // 3 → 3 |
** | Power | 2 ** 3 → 8 |
Example:
2️⃣ Assignment Operators
Used to assign and update variables.
| Operator | Meaning | Example |
|---|---|---|
= | Assign value | x = 10 |
+= | Add and assign | x += 5 → x = x + 5 |
-= | Subtract and assign | x -= 5 |
*= | Multiply and assign | x *= 5 |
/= | Divide and assign | x /= 5 |
//=, %=, **= | Other combinations |
Example:
3️⃣ Comparison Operators
Used to compare values — result is True or False.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal | 5 != 2 → True |
> | Greater than | 5 > 2 → True |
< | Less than | 5 < 2 → False |
>= | Greater or equal | 5 >= 5 → True |
<= | Less or equal | 3 <= 5 → True |
Example:
4️⃣ Logical Operators
Used to combine conditions.
| Operator | Meaning |
|---|---|
and | True if both are True |
or | True if at least one is True |
not | Reverses True ↔ False |
Example:
5️⃣ Identity Operators
Used to compare memory locations, not values.
| Operator | Meaning |
|---|---|
is | True if objects are same memory reference |
is not | False if objects are same |
Example:
6️⃣ Membership Operators
Used to check if a value exists in sequence (string, list, tuple, etc.)
| Operator | Meaning |
|---|---|
in | True if value exists |
not in | True if does NOT exist |
Example:
7️⃣ Bitwise Operators (Advanced)
Works on bits (0,1).
| Operator | Meaning | Example |
|---|---|---|
& | AND | 5 & 3 → 1 |
| ` | ` | OR |
^ | XOR | 5 ^ 3 → 6 |
~ | NOT | ~5 → -6 |
<< | Left shift | 2 << 1 → 4 |
>> | Right shift | 4 >> 1 → 2 |
Example:
🎯 Operator Precedence (Order of Execution)
Like math rules (BODMAS):
Highest → Lowest:
Example:
