Operators are special symbols or keywords used to perform operations on variables and values. Python supports various types of operators to handle different operations.
1. Arithmetic Operators
Used for basic mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 5 / 2 = 2.5 |
% | Modulus (Remainder) | 5 % 2 = 1 |
** | Exponentiation (Power) | 5 ** 2 = 25 |
// | Floor Division | 5 // 2 = 2 |
2. Comparison Operators
Used to compare values, returning True
or False
.
Operator | Description | Example |
---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal to | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater than or equal to | 5 >= 5 → True |
<= | Less than or equal to | 5 <= 3 → False |
3. Logical Operators
Used to combine conditional statements.
Operator | Description | Example |
---|---|---|
and | Returns True if both are true | (5 > 3 and 2 < 4) → True |
or | Returns True if one is true | (5 > 3 or 2 > 4) → True |
not | Reverses the result | not(5 > 3) → False |
4. Assignment Operators
Used to assign values to variables.
Operator | Description | Example |
---|---|---|
= | Assign | x = 5 |
+= | Add and assign | x += 3 → x = 8 |
-= | Subtract and assign | x -= 2 → x = 6 |
*= | Multiply and assign | x *= 2 → x = 12 |
/= | Divide and assign | x /= 3 → x = 4 |
//= | Floor divide and assign | x //= 2 → x = 2 |
%= | Modulus and assign | x %= 2 → x = 0 |
**= | Exponent and assign | x **= 2 → x = 25 |
5. Bitwise Operators
Used to perform operations on binary numbers.
Operator | Description | Example |
---|---|---|
& | AND | 5 & 3 → 1 |
` | ` | OR |
^ | XOR | 5 ^ 3 → 6 |
~ | NOT | ~5 → -6 |
<< | Left shift | 5 << 1 → 10 |
>> | Right shift | 5 >> 1 → 2 |
6. Membership Operators
Used to test membership in a sequence like a list or string.
Operator | Description | Example |
---|---|---|
in | Returns True if value is found | "a" in "apple" → True |
not in | Returns True if value is not found | "x" not in "apple" → True |
7. Identity Operators
Used to compare memory locations of two objects.
Operator | Description | Example |
---|---|---|
is | Returns True if same object | x is y → True |
is not | Returns True if different objects | x is not y → True |
Examples:
# Arithmetic
a, b = 10, 3
print(a + b) # Output: 13
print(a % b) # Output: 1
# Comparison
print(a > b) # Output: True
# Logical
print(a > 5 and b < 5) # Output: True
# Membership
fruits = ["apple", "banana"]
print("apple" in fruits) # Output: True
# Identity
x = [1, 2, 3]
y = x
print(x is y) # Output: True
Understanding operators allows you to perform a wide range of operations and make your Python programs dynamic and functional.
No responses yet