What are Operators?
Operators are special symbols or keywords used to perform operations on values and variables.
For example, we use operators to perform calculations, compare values, and check conditions.
Types of Operators in Python
Python has six main types of operators:
- Arithmetic Operators
- Relational (Comparison) Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Conditional (Ternary) Operator
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
| Operator | Description |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
// |
Floor Division |
% |
Modulus (Remainder) |
** |
Exponentiation (Power) |
Example:
a = 10
b = 3
print(a + b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output:
13
3.3333333333333335
3
1
1000
Note: / performs normal division, // returns the floor value, % gives the remainder, and ** calculates power.
2. Relational (Comparison) Operators
These operators compare two values and return either True or False.
| Operator | Meaning |
|---|---|
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
== |
Equal to |
!= |
Not equal to |
Example:
a = 10
b = 20
print(a > b)
print(a < b)
print(a == b)
print(a != b)
Output:
False
True
False
True
3. Logical Operators
Logical operators are used to combine conditions.
Python provides three logical operators:
-
and– True when both conditions are True. -
or– True when at least one condition is True. -
not– Reverses the result.
Example:
age = 22
has_id = True
print(age >= 18 and has_id)
print(age >= 18 or has_id)
print(not has_id)
Output:
True
True
False
4. Bitwise Operators
Bitwise operators perform operations on the binary representation of numbers (0s and 1s).
| Operator | Description |
|---|---|
& |
Bitwise AND |
| `\ | ` |
^ |
Bitwise XOR |
~ |
Bitwise NOT |
<< |
Left Shift |
>> |
Right Shift |
Example:
a = 5
b = 3
print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 1)
print(a >> 1)
Output:
1
7
6
-6
10
2
5. Assignment Operators
Assignment operators are used to assign or update values in variables.
| Operator | Example | Equivalent |
|---|---|---|
= |
a = 10 |
Assign value |
+= |
a += 5 |
a = a + 5 |
-= |
a -= 5 |
a = a - 5 |
*= |
a *= 5 |
a = a * 5 |
/= |
a /= 5 |
a = a / 5 |
%= |
a %= 5 |
a = a % 5 |
Example:
a = 10
a += 5
print(a)
a *= 2
print(a)
Output:
15
30
These shorthand operators make updating variable values easier.
6. Conditional (Ternary) Operator
The ternary operator allows us to write a simple if-else condition in a single line.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 20
result = "Eligible" if age >= 18 else "Not Eligible"
print(result)
Output:
Eligible
If the condition is True, the first value is returned; otherwise, the second value is returned.
Top comments (0)