In Python (programming language), operators are special symbols that perform operations on variables and values. They are essential for performing mathematical, logical, and comparison operations in your programs.
π’ 1οΈβ£ Arithmetic Operators
Used to perform mathematical calculations.
| Operator | Description | Example | Output |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 3 | 18 |
/ | Division | 10 / 2 | 5.0 |
// | Floor Division | 10 // 3 | 3 |
% | Modulus (remainder) | 10 % 3 | 1 |
** | Exponent | 2 ** 3 | 8 |
Example Program:
x = 10
y = 3print("Addition:", x + y)
print("Modulus:", x % y)
print("Exponent:", x ** y)
βοΈ 2οΈβ£ Comparison Operators
Used to compare values. The result is always True or False.
| Operator | Description | Example |
|---|---|---|
== | Equal to | 5 == 5 β True |
!= | Not equal | 5 != 3 β True |
> | Greater than | 10 > 5 β True |
< | Less than | 3 < 7 β True |
>= | Greater or equal | 5 >= 5 β True |
<= | Less or equal | 4 <= 7 β True |
π 3οΈβ£ Assignment Operators
Used to assign values to variables, often combined with arithmetic.
| Operator | Example | Meaning |
|---|---|---|
= | x = 5 | Assign 5 to x |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x – 2 |
*= | x *= 4 | x = x * 4 |
/= | x /= 2 | x = x / 2 |
%= | x %= 3 | x = x % 3 |
**= | x **= 2 | x = x ** 2 |
//= | x //= 3 | x = x // 3 |
π 4οΈβ£ Logical Operators
Used to combine conditions.
| Operator | Description | Example |
|---|---|---|
and | True if both conditions are True | True and False β False |
or | True if any condition is True | True or False β True |
not | Inverts the value | not True β False |
π§© 5οΈβ£ Identity Operators
Used to check if two variables refer to the same object.
| Operator | Example | Output |
|---|---|---|
is | x is y | True if same object |
is not | x is not y | True if not same object |
π¦ 6οΈβ£ Membership Operators
Check if a value exists in a sequence (like a list, tuple, or string).
| Operator | Example | Output |
|---|---|---|
in | 'a' in 'apple' | True |
not in | 'b' not in 'apple' | True |
π¨ Example Program Using Multiple Operators
x = 10
y = 3# Arithmetic
print("Addition:", x + y)
print("Exponent:", x ** y)# Comparison
print("Is x greater than y?", x > y)# Logical
print("x > 5 and y < 5:", x > 5 and y < 5)# Membership
fruits = ["apple", "banana"]
print("Is 'apple' in fruits?", "apple" in fruits)
β Key Points
- Operators perform actions on variables or values.
- Arithmetic β numbers
- Comparison β True/False
- Assignment β store or update values
- Logical β combine conditions
- Identity & Membership β check object or sequence membership