Operators in Python
What is an Operator in Python?
A Python operator is a symbol that tells the interpreter to perform specific operations such as mathematical calculations, value comparisons, or logic-based decisions.
Python includes several categories of operators:
Operator Type | Description |
---|---|
Arithmetic Operators | Perform basic math operations |
Assignment Operators | Assign values to variables |
Comparison Operators | Compare values (return Boolean results) |
Logical Operators | Combine conditional statements |
Bitwise Operators | Perform bit-level operations |
Membership Operators | Test for membership in a sequence |
Identity Operators | Compare memory locations of objects |
1. Arithmetic Operator
These are used for mathematical operations.
Operator | Name | Description | Example | Output |
---|---|---|---|---|
+ | Addition | Adds two operands | 3 + 2 | 5 |
- | Subtraction | Subtracts the second operand from the first | 5 - 1 | 4 |
* | Multiplication | Multiplies both operands | 2 * 3 | 6 |
/ | Division | Divides the first operand by the second | 10 / 2 | 5.0 |
// | Floor Division | Returns the quotient in integer format | 7 // 2 | 3 |
% | Modulus | Returns the remainder | 5 % 2 | 1 |
** | Exponentiation | Raises the first operand to the power of the second | 2 ** 3 | 8 |
1. Addition (+)
The +
operator adds two numbers.
a = 10
b = 5
result = a + b
print(result)
Output:
15
Explanation: The sum of 10 and 5 is 15.
2. Subtraction (-)
The -
operator subtracts the second operand from the first.
a = 10
b = 5
result = a - b
print(result)
Output:
5
Explanation: The result of 10 - 5 is 5.
3. Multiplication (*)
The *
operator multiplies two numbers.
a = 10
b = 5
result = a * b
print(result)
Output:
50
Explanation: The product of 10 and 5 is 50.
4. Division (/)
The /
operator divides the first number by the second and returns the result as a floating-point
number (even if the result is a whole number).
a = 10
b = 3
result = a / b
print(result)
Output:
3.3333333333333335
Explanation: The result of dividing 10 by 3 is approximately 3.333.
5. Floor Division (//)
The //
operator divides the first number by the second and returns the largest integer less than
or equal to the result (i.e., the floor value).
a = 10
b = 3
result = a // b
print(result)
Output:
3
Explanation: The result of 10 // 3 is 3, as the floor value of 3.333 is 3.
6. Modulus (%)
The %
operator returns the remainder of the division of the first number by the second.
a = 10
b = 3
result = a % b
print(result)
Output:
1
Explanation: The remainder of dividing 10 by 3 is 1.
7. Exponentiation (**)
The **
operator is used to raise the first number to the power of the second.
a = 2
b = 3
result = a ** b
print(result)
Output:
8
Explanation: 2 raised to the power of 3 is 8 (i.e., 2^3 = 8).
2. Assignment Operators
Used to assign values to variables.
Operator | Description | Example | Equivalent To |
---|---|---|---|
= | Assign value | x = 10 | x = 10 |
+= | Add and assign | x += 5 | x = x + 5 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 4 | x = x * 4 |
/= | Divide and assign | x /= 2 | x = x / 2 |
//= | Floor divide and assign | x //= 3 | x = x // 3 |
%= | Modulus and assign | x %= 2 | x = x % 2 |
**= | Exponent and assign | x **= 3 | x = x ** 3 |
Python Assignment Operators
1. Simple Assignment (=)
Assigns a value to a variable.
x = 10
print(x)
Output:
10
Assigns the value 10 to variable x.
2. Add and Assign (+=)
Adds a value to the variable and assigns the result.
x = 10
x += 5
print(x)
Output:
15
Adds 5 to x and stores the result in x.
3. Subtract and Assign (-=)
Subtracts a value from the variable and assigns the result.
x = 15
x -= 4
print(x)
Output:
11
Subtracts 4 from x and updates x.
4. Multiply and Assign (*=)
Multiplies the variable by a value and assigns the result.
x = 6
x *= 3
print(x)
Output:
18
Multiplies x by 3 and stores the result in x.
5. Divide and Assign (/=)
Divides the variable by a value and assigns the float result.
x = 20
x /= 4
print(x)
Output:
5.0
Divides x by 4 and stores the float result in x.
6. Floor Divide and Assign (//=)
Performs floor division and assigns the integer result.
x = 20
x //= 3
print(x)
Output:
6
Performs floor division (20 // 3 = 6) and assigns the result.
7. Modulus and Assign (%=)
Calculates the remainder and assigns it to the variable.
x = 10
x %= 3
print(x)
Output:
1
Calculates remainder (10 % 3 = 1) and assigns it to x.
8. Exponent and Assign (**=)
Raises the variable to a power and assigns the result.
x = 2
x **= 4
print(x)
Output:
16
Raises x to the power of 4 (2 ** 4 = 16) and assigns it to x.
3. Comparison (Relational) Operators
Used to compare two values.
Operator | Description | Example | Output |
---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 5 | True |
< | Less than | 3 < 2 | False |
>= | Greater than or equal to | 4 >= 4 | True |
<= | Less than or equal to | 2 <= 1 | False |
1. Equal to (==)
Checks if two values are equal.
x = 10
y = 10
print(x == y)
Output:
True
2. Not Equal to (!=)
Checks if two values are not equal.
x = 10
y = 5
print(x != y)
Output:
True
3. Greater Than (>)
Checks if the left operand is greater than the right operand.
x = 15
y = 10
print(x > y)
Output:
True
4. Less Than (<)< /h3>
Checks if the left operand is less than the right operand.
x = 5
y = 8
print(x < y)
Output:
True
5. Greater Than or Equal To (>=)
Checks if the left operand is greater than or equal to the right operand.
x = 7
y = 7
print(x >= y)
Output:
True
6. Less Than or Equal To (<=)< /h3>
Checks if the left operand is less than or equal to the right operand.
x = 4
y = 9
print(x <= y)
Output:
True
When to Use Comparison Operators
- In
if
,elif
, andelse
statements - In
while
andfor
loops - In filtering and conditional logic
- When checking conditions in functions
4. Logical Operators
Used to combine conditional expressions.
Operator | Description | Example | Output |
---|---|---|---|
and | Returns True if both conditions are true | True and False | False |
or | Returns True if at least one condition is true | True or False | True |
not | Reverses the result (True becomes False) | not True | False |
1. and Operator
Returns True
only if both conditions are true.
Example:
x = 7
print(x > 5 and x < 10)
Output:
True
Both x > 5
and x < 10
are true.
Another Example:
x = 4
print(x > 5 and x < 10)
Output:
False
Because x > 5
is false, the whole expression becomes false.
2. or Operator
Returns True
if at least one condition is true.
Example:
x = 4
print(x > 5 or x < 10)
Output:
True
Only x < 10
is true, so the result is true.
Another Example:
x = 12
print(x < 5 or x < 10)
Output:
False
Both conditions are false, so the result is false.
3. not Operator
Returns the opposite of the result.
Example:
x = 8
print(not(x > 5))
Output:
False
Because x > 5
is True
, not True
becomes False
.
When to Use Logical Operators
- In
if-elif-else
conditions - For complex decision-making logic
- Inside loops to manage multiple checks
- In filtering, validation, and form handling
5. Bitwise Operators
Operate on binary numbers.
Operator | Name | Example | Output | Description |
---|---|---|---|---|
& | AND | 5 & 3 | 1 | Sets each bit to 1 if both bits are 1 |
| | OR | 5 | 3 | 7 | Sets each bit to 1 if one of the bits is 1 |
^ | XOR | 5 ^ 3 | 6 | Sets each bit to 1 if only one of the bits is 1 |
~ | NOT | ~5 | -6 | Inverts all the bits |
<< | Left Shift | 5 << 1 | 10 | Shifts bits to the left (adds zeros on the right) |
>> | Right Shift | 5 >> 1 | 2 | Shifts bits to the right (discards bits on the right) |
1. Bitwise AND (&)
a = 5 # 0101
b = 3 # 0011
print(a & b)
Output:
1
Explanation: 0101 & 0011 = 0001 → 1
2. Bitwise OR (|)
a = 5 # 0101
b = 3 # 0011
print(a | b)
Output:
7
Explanation: 0101 | 0011 = 0111 → 7
3. Bitwise XOR (^)
a = 5 # 0101
b = 3 # 0011
print(a ^ b)
Output:
6
Explanation: 0101 ^ 0011 = 0110 → 6
4. Bitwise NOT (~)
a = 5
print(~a)
Output:
-6
Explanation: ~5 returns -6 due to two's complement representation.
5. Left Shift (<<)
a = 5 # 0101
print(a << 1)
Output:
10
Explanation: 0101 << 1 = 1010 → 10
6. Right Shift (>>)
a = 5 # 0101
print(a >> 1)
Output:
2
Explanation: 0101 >> 1 = 0010 → 2
Use Cases of Bitwise Operators
- Fast arithmetic (e.g., multiplication/division by powers of 2)
- Permissions and flag systems
- Cryptography and hashing algorithms
- Binary masking
Membership Operators
Used to test if a value exists in a sequence (like a list or string).
Operator | Description | Example | Output |
---|---|---|---|
in | Returns True if the value exists in a sequence | 'a' in 'apple' | True |
not in | Returns True if the value does not exist in a sequence | 'z' not in 'cat' | True |
6. Python Membership Operators
1. in Operator
Used to check if a value exists in a sequence.
Example 1: Using in with Strings
fruit = "banana"
print("a" in fruit)
Output:
True
Explanation: "a" is found in "banana".
Example 2: Using in with Lists
colors = ["red", "green", "blue"]
print("green" in colors)
Output:
True
2. not in Operator
Used to check if a value does NOT exist in a sequence.
Example 1: Using not in with Strings
message = "hello world"
print("z" not in message)
Output:
True
Example 2: Using not in with Lists
numbers = [1, 2, 3, 4, 5]
print(10 not in numbers)
Output:
True
Example 3: Using in with Dictionaries (Checks keys only)
person = {"name": "Alice", "age": 25}
print("name" in person)
Output:
True
Note: Membership operators only check keys in dictionaries, not values.
Use Cases of Membership Operators
- Check if an item exists before performing operations
- Validate user input against allowed values
- Filter data using conditionals
- Efficient in list and string searching
7. Identity Operators
Identity operators are used to compare the memory location (identity) of two objects. They are typically used when you want to check if two variables point to the same object in memory.
Operator | Description | Example | Output |
---|---|---|---|
is | Returns True if both variables point to the same object in memory | x is y | True or False |
is not | Returns True if both variables point to different objects in memory | x is not y | True or False |
1. is Operator
Used to compare if two variables point to the same object in memory.
Example 1: Using is with Variables
a = [1, 2, 3]
b = a
print(a is b)
Output:
True
Since a
and b
point to the same list object in memory, a is b
returns True
.
Example 2: Using is with Different Objects
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
Output:
False
Even though both lists contain the same elements, they are two different objects in memory. Hence,
a is b
returns False
.
2. is not Operator
Used to compare if two variables point to different objects in memory.
Example 1: Using is not with Variables
x = [1, 2]
y = [1, 2]
print(x is not y)
Output:
True
Even though x
and y
have the same values, they are stored in different memory
locations, so x is not y
returns True
.
Example 2: Using is not with Same Object
x = [1, 2]
y = x
print(x is not y)
Output:
False
Since both x
and y
refer to the same list object in memory,
x is not y
returns False
.
When to Use Identity Operators
- Memory optimization: To check if two variables reference the same object (especially useful with immutable types like strings, integers, etc.)
- Object comparison: When you want to determine if two variables are not referring to the same object
- Singleton pattern: To check if an object is the unique instance (e.g.,
None
or a single shared instance)