In Python, operators are special symbols that carry out arithmetic, logical, relational, or other specific operations on one or more operands. They play a fundamental role in performing operations on data, manipulating values, comparing variables, and more. In this guide, we'll delve into the various operators in Python and provide examples to illustrate their usage.
1. Arithmetic Operators:
Arithmetic operators are utilized for mathematical calculations.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
** | Exponentiation |
// | Floor Division |
Examples:
x = 15
y = 4
print(x + y) # Outputs: 19
print(x - y) # Outputs: 11
print(x * y) # Outputs: 60
print(x / y) # Outputs: 3.75
print(x % y) # Outputs: 3
print(x ** y) # Outputs: 50625
print(x // y) # Outputs: 3
2. Comparison Operators:
Comparison operators are used to compare values.
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Examples:
x = 5
y = 3
print(x == y) # Outputs: False
print(x != y) # Outputs: True
print(x < y) # Outputs: False
print(x > y) # Outputs: True
print(x <= y) # Outputs: False
print(x >= y) # Outputs: True
3. Logical Operators:
Logical operators are employed for boolean operations.
Operator | Description |
---|---|
and | Logical AND |
or | Logical OR |
not | Logical NOT |
Examples:
x = True
y = False
print(x and y) # Outputs: False
print(x or y) # Outputs: True
print(not x) # Outputs: False
4. Assignment Operators:
Used to assign values to variables.
Operator | Description |
---|---|
= | Assignment |
+= | Add and assign |
-= | Subtract and assign |
*= | Multiply and assign |
/= | Divide and assign |
%= | Modulus and assign |
**= | Exponentiation and assign |
//= | Floor division and assign |
Examples:
x = 5
x += 3
print(x) # Outputs: 8
x *= 2
print(x) # Outputs: 16
5. Identity Operators:
Used to compare the memory locations of two objects.
Operator | Description |
---|---|
is | Returns true if both variables are the same object |
is not | Returns true if both variables are not the same object |
Examples:
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # Outputs: True
print(x is y) # Outputs: False
print(x is not y) # Outputs: True
6. Membership Operators:
Used to test whether a value or variable is in a sequence (string, list, tuple, etc.).
Operator | Description |
---|---|
in | Returns true if a sequence with the specified value is present in the object |
not in | Returns true if a sequence with the specified value is not present in the object |
Examples:
fruits = ["apple", "banana"]
print("apple" in fruits) # Outputs: True
print("cherry" not in fruits) # Outputs: True