Table of Contents
In Python, operators are special symbols or keywords that tell the interpreter to perform specific operations on one or more operands (values or variables).
x = 8
y = 5
print(x + y)
# Output: 13
Analysis:
In the above program ‘+’ is an operator that adds variables x and y.
Types of Python Operators
1. Arithmetic Operators
Arithmetic operators are symbols used in programming and mathematics to perform calculations on numeric values (operands).
| Operators | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus(remainder) |
| ** | Exponentiation |
| // | Floor Division (it divides and rounds and rounds down to the nearest whole number) |
Write a python program for a simple calculator using Python arithmetic Operators
num1 = 15.0
num2 = 4.0
# Addition
addition = num1 + num2
print(f"1. Addition: = {addition}") # 19.0
# Subtraction
subtraction = num1 - num2
print(f"2. Subtraction: = {subtraction}") # 11.0
# Multiplication
multiplication = num1 * num2
print(f"3. Multiplication: = {multiplication}") # 60.0
# Division
division = num1 / num2
print(f"4. Division: = {division}") # 3.75
# Modulus
modulus = num1 % num2
print(f"5. Modulus: = {modulus}") # 3.0
# xponentiation
exponentiation = num1 ** num2
print(f"6. Exponentiation: = {exponentiation}") # 50625.0
# Floor Division
floor_division_result = num1 // num2
print(f"7. Floor Division: = {floor_division_result}") # 3.0
2. Comparison Operators
Comparison Operators are always used to compare two or more values and their result is always true or false.
| Operators | Description |
|---|---|
| == | Equal to |
| != | Not equal |
| > | Greater Than |
| < | Smaller Than |
| >= | Greater than or equal to |
| <= | Smaller than or equal to |
a = 25
b = 15
c = 25
print(f" A = {a}") # 25
print(f" B = {b}") # 15
print(f" C = {c}") # 25
print("All results will be displayed as True or False")
# Equal to
result = a == b
print(f"1. A == B: {result}") # False
result_c = a == c
print(f"2. A == C: {result_c}") # True
# not equal
result = a != b
print(f"3. A != B: {result}") # True
# Greater than
result = a > b
print(f"4. A > B: {result}") # True
# Less than
result = a < b
print(f"5. A < B: {result}") # False
# Greater than or equal to
result = a >= c
print(f"6. A >= C: {result}") # True
# Less than or equal to
result = b <= c
print(f"7. B <= C: {result}") # True
3. Logical Operators
Logical Operators are mainly used to combine two or more Boolean statements or any comparison results. Logical Operators are used in if conditions.
| Operations | Description |
|---|---|
| and | returns true if both are True |
| or | returns true if one is True |
| not | reverses the result |
Consider two statements
A = 10 > 5; B = 10 < 8
Write a python program to perform AND, OR, NOT operation between A and B.
A = 10 > 5
B = 10 < 8
print(f" A (10 > 5): {A}") # True
print(f" B (10 < 8): {B}") # False
# True if BOTH are True.
result_and = A and B
print(f"(A and B): {result_and}") # (A and B): False
# True if AT LEAST ONE is True.
result_or = A or B
print(f"(A or B): {result_or}") # (A or B): True
# Reverses the state of the operand.
result_not = not B
print(f"(not B): {result_not}") # (not B): True
4. Assignment Operators
Assignment operators are used to assign a value to a variable. They combine standard arithmetic operators with the assignment operator (=). They are like a shortcut for updating the value of the variable.
| Operator | Example | Equivalent To |
|---|---|---|
| = | x = 10 | x = 10 |
| += | x += 2 | x = x + 2 |
| -= | x -= 2 | x = x - 2 |
| *= | x *= 2 | x = x * 2 |
| /= | x /= 2 | x = x / 2 |
| %= | x %= 3 | x = x % 3 |
| **= | x **= 4 | x = x ** 4 |
| //= | x //= 3 | x = x // 3 |
x = 20
x += 5 # 20 + 5 = 25
print(f"1. X += 5: {x}")
x -= 7 # 25 - 7 = 18
print(f"2. X -= 7 : {x}")
x *= 2 # 18 * 2 = 36
print(f"3. X *= 2 : {x}")
x /= 3 # 36 / 3 = 12.0
print(f"4. X /= 3 : {x}")
x %= 5 # 12 % 5= 2.0
print(f"5. X %= 5 : {x}")
x **= 2 # 2 ** 2 = 4.0
print(f"6. X **= 2 : {x}")
x = 17 # Resetting for a clear floor division example
x //= 5 # 17 // 5 = 3
print(f"7. X //= 5 : {x}")
5. Bitwise Operators
They are used to perform bit-level operations on integers in Python.
Operator
Bitwise & (AND):
1 & 1 =1, 0 & 1 = 0
5 & 3 =1
Binary Logic
5: 0101
3: 0011
Result: 0001 only the rightmost bit has 1 and 1 in 5 and 3 and hence the result is 1.
Bitwise OR (|):
5|3 = 7
Binary Logic
0 OR 1 = 1 if any one bit is 1 the result is 1
5: 0101
3: 0011
Result: 0111 = 7
Bitwise XOR (^):
5 ^ 3 = 6
Binary Logic:
1XOR 0 =1 if the bits are different the result is 1
5: 0101
3: 0011
Result: 0110 0110=6
Bitwise NOT ( ~ )
The core action is it flips all the bits. (0 becomes 1 and 1 becomes 0)
To perform the bit flip {NOT}, the computer must work with a complete, consistent number of bits (like 8 bits or more)
0 is considered positive
1 is considered negative
Formula: ~X = – (X + 1)
Consider 8 bits in computer memory. The bitwise Not is performed as
Binary logic:
Example
~5 = 0000 0101 -> 1111 1010
Two’s Complement Rule: To find the decimal value of a negative number in Two’s Complement, the computer:
- flips it back 0000 0101
- adds 1 =5+1=6
- Makes positive result as negative.
– (5+1) = -6
Example 2:
~(-8) -(-8+1)=7
Bitwise shift operators (<< and >>)
Left shift
(5<<1)=10
0101 = 1010 (All bits move left 1 position. And 0 is added on the right)
(5<<2) 0101 = 10100 (
All bits move left 2 positions total. Two 0s are added on the right.
Right shift
(5 >> 1)
0101 = 0010 (· Moves every bit (1) position to the right, and the bit on the far right is dropped)
Write a Python program to perform all the bitwise operations considering two variables: A = 12 and B = 5.
A = 12
B = 5
print(f"Number A: {A} (Binary: {A:08b})") # 00001100
print(f"Number B: {B} (Binary: {B:08b})") # 00000101
result_and = A & B
print(f"1. A & B (AND): {result_and}") # A & B (AND): 4
result_or = A | B
print(f"2. A | B (OR): {result_or}") # A | B (OR): 13
result_xor = A ^ B
print(f"3. A ^ B (XOR): {result_xor}") # A ^ B (XOR): 9
result_not_A = ~A
print(f"4. ~A (NOT): {result_not_A}") # ~A (NOT): -13
result_left_shift = A << 2
print(f"5. A << 2 (Left Shift): {result_left_shift}") # A << 2 (Left Shift): 48
result_right_shift = A >> 1
print(f"6.A >> 1 (Right Shift): {result_right_shift}") # A >> 1 (Right Shift): 6
6. Membership Operators
Used to check if a value is part of a sequence (like a list, tuple, or string).
Operator
In: returns true if value is found
Eg: ‘a’ in apple =true
not in: true if not identical
Eg: ‘v’ not in apple = true
languages = ["Python", "Java", "C++", "JavaScript", "Go"]
check_in_1 = "Python" in languages
print(f"1. Is 'Python' in the list?: {check_in_1}")
check_not_in_1 = "PHP" not in languages
print(f"2. Is 'PHP' NOT in the list?: {check_not_in_1}")
check_not_in_2 = "Java" not in languages
print(f"3. Is 'Java' NOT in the list? : {check_not_in_2}")
# Output
# 1. Is 'Python' in the list?: True
# 2. Is 'PHP' NOT in the list?: True
# 3. Is 'Java' NOT in the list? : False
7. Identity Operators
They are used to compare the memory locations of two objects.
| Operator | Description | Example | Output |
|---|---|---|---|
| is | True if objects are identical | x is y | True / False |
| is not | True if not identical | x is not y | True / False |
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y) # True
print(x is z) # False
print(x is y) –> True:
x = [1, 2, 3]creates a new list object in memory, and the variablexpoints to it.y = xdoes not create a new list. It makes the variableypoint to the same list object in memory that x is already pointing to. The is operator checks the object identity (whether they share the same memory address) and because both x and y point to the same list the result is True.
print(x is z) –> False
- x = [1, 2, 3] is the original list.
z = [1, 2, 3] creates a new distinct list object in memory. Even though the contents are identical to the list pointed to by x they are stored in two different places in the computer’s memory. Theisoperator checks if they are the same object. Since x and z point to different objects in memory the result is False.
Ternary Operators
The ternary operator in Python is often used as a shorthand for a simple if-else statement.
score = 75
status = "Pass" if score >= 60 else "Fail"
print(status) # Pass
Operator Precedence and Associativity
Operator precedence is the rule that dictates the order in which different types of operators in an expression are evaluated. Operators with higher precedence are evaluated before operators with lower precedence.
Associativity is the rule that determines the order of evaluation for operators that have the same precedence (i.e., when precedence alone cannot resolve the order). It defines whether evaluation proceeds from left-to-right (left-associative) or right-to-left (right-associative).
| Precedence Level | Operators | Description |
|---|---|---|
| 1 | ( ) | Parentheses |
| 2 | * * | Exponentiation |
| 3 | *, /, //, % | Multiplication/Division |
| 4 | +, - | Addition/Subtraction |
| 5 | ==, !=, >=, <=, <, > | Comparison |
| 6 | and, or, not | Logical operations |
In Python, the vast majority of binary operators are left-associative. The main exceptions you need to remember are exponentiation (**) and assignment operators (=, +=, etc.), which are right-associative.
Consider a few examples below.
x = 2
y = 3
z = 2
result = x ** y ** z
print(result) # 512
A = 2
B = 3
C = 15
# Goal: Predict the final value of X.
X = A ** B ** 2 > 100 or C / 5 < 3 and A * 5 != 10
print(f"Final Result (X): {X}") # True
| Step | Operation | Formula | Result | Current Simplified Expression | Precedence Rule Applied |
|---|---|---|---|---|---|
| 1 | Exponentiation | B ** 2 | 3^2 = 9 | A ** 9 > 100 or C/5 < 3 and A * 5!= 10 | ** is Right-Associative |
| 2 | Exponentiation | A ** 9 | 2^9 = 512 | 512 > 100 or C / 5 < 3 and A * 5!= 10 | ** (Highest) |
| 3 | Division | C / 5 | 15 / 5 =3 | 512 > 100 or 3 < 3 and A * 5!=10 | / |
| 4 | Multiplication | A * 5 | 2 * 5 = 10 | 512 > 100 or 3 < 3 and 10 != 10 | * |
| 5 | Comparison | 512 > 100 | True | True or 3 < 3 and 10 != 10 | >, <, != |
| 6 | Comparison | 3 < 3 | False | True or False and 10 != 10 | >, <, != |
| 7 | Comparison | 10 != 10 | False | True or False and False | >, <, != |
| 8 | Logical AND | False and False | False | True or False | and (Higher than or) |
| 9 | Logical OR | True or False | True | X = True | or (Lowest Logical) |
FAQ (Frequently Asked Questions)
1) What is the Python remainder operator?
The remainder or modulus operator is ‘%’ in Python. It returns the remainder when a number is divided by the other.
Example: 10 % 3 = 1.
2) What are conditional operators in Python?
Conditional operators (also known as relational operators or comparison operators) are used to compare two values and return a Boolean result (True or False).
3) What is the Python and, or, not operator?
These are logical operators used to combine or reverse conditions:
and → True if both conditions are true
or →returns True if one condition is true
not → Reverses the condition
4) What is the Increment operator in Python?
Python does not have ++ or — like C or Java. To increment we use: x += 1
5) What is operator overloading in Python?
Operator overloading lets you redefine/extend how operators work for user-defined classes.
Example: redefining + for a custom class using __add__().
6) What arithmetic operators cannot be used with strings in Python?
You cannot use: – (subtraction), /, //, %, ** etc with another string.
You can only use: + (string concatenation) * (string repetition with an integer).
7) What is a membership operator in Python?
Membership operators check if a value exists inside a sequence: in → True if value is present not in → True if value is not present.