Types of Operators in Python
In Python, operators are special symbols used to perform operations on variables and values. They are an essential part of programming because they allow calculations, comparisons, and logical decisions.
Python provides several types of operators.
Arithmetic Operators
These operators perform mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 6 / 3 = 2.0 |
% | Modulus (remainder) | 5 % 2 = 1 |
** | Exponent (power) | 2 ** 3 = 8 |
// | Floor division | 7 // 2 = 3 |
Example
a = 10
b = 3
print(a + b)
print(a % b)
Comparison (Relational) Operators
These operators compare two values and return True or False.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 |
!= | Not equal | 5 != 3 |
> | Greater than | 7 > 5 |
< | Less than | 3 < 5 |
>= | Greater than or equal | 5 >= 5 |
<= | Less than or equal | 3 <= 4 |
Example
x = 5
y = 10
print(x < y)
Logical Operators
Logical operators are used to combine conditional statements.
| Operator | Meaning |
|---|---|
and | Returns True if both conditions are True |
or | Returns True if one condition is True |
not | Reverses the result |
Example
a = 5
b = 10
print(a < b and b > 0)
Assignment Operators
These operators are used to assign values to variables.
| Operator | Example |
|---|---|
= | x = 5 |
+= | x += 3 |
-= | x -= 2 |
*= | x *= 4 |
/= | x /= 2 |
Example
x = 5
x += 3
print(x)
Membership Operators
Used to check if a value exists in a sequence.
| Operator | Meaning |
|---|---|
in | Value exists |
not in | Value does not exist |
Example
list = [1,2,3,4]
print(3 in list)
Identity Operators
Used to compare the memory location of objects.
| Operator | Meaning |
|---|---|
is | Objects are the same |
is not | Objects are not the same |
Example
x = 5
y = 5
print(x is y)
Summary Table
| Operator Type | Purpose |
|---|---|
| Arithmetic | Mathematical calculations |
| Comparison | Compare values |
| Logical | Combine conditions |
| Assignment | Assign values |
| Membership | Check values in sequence |
| Identity | Compare memory location |
Comments
Post a Comment