Python Operators Guide (For Beginners)
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, etc.
• + : Addition → 5 + 2 = 7
• - : Subtraction → 5 - 2 = 3
• * : Multiplication → 5 * 2 = 10
• / : Division → 5 / 2 = 2.5
• // : Floor Division → 5 // 2 = 2
• % : Modulus (Remainder) → 5 % 2 = 1
• ** : Exponentiation (Power) → 2 ** 3 = 8
2. Comparison Operators
Comparison operators are used to compare two values and return True or False.
• == : Equal → 5 == 5 (True)
• != : Not Equal → 5 != 3 (True)
• > : Greater Than → 5 > 3 (True)
• < : Less Than → 5 < 3 (False)
• >= : Greater or Equal → 5 >= 5 (True)
• <= : Less or Equal → 3 <= 5 (True)
3. Assignment Operators
Assignment operators are used to assign values to variables.
• = : Assign → x = 5
• += : Add and assign → x += 2
• -= : Subtract and assign → x -= 2
• *= : Multiply and assign → x *= 2
• /= : Divide and assign → x /= 2
• //= : Floor divide and assign → x //= 2
• %= : Modulus and assign → x %= 2
• **= : Exponent and assign → x **= 2
4. Logical Operators
Logical operators are used to combine conditional statements.
• and : Returns True if both conditions are true
• or : Returns True if one of the conditions is true
• not : Reverses the result
5. Bitwise Operators
Bitwise operators work on bits (0s and 1s).
• & : AND → 5 & 3 = 1
• | : OR → 5 | 3 = 7
• ^ : XOR → 5 ^ 3 = 6
• ~ : NOT → ~5 = -6
• << : Left shift → 5 << 1 = 10
• >> : Right shift → 5 >> 1 = 2
6. Membership Operators
Used to test if a sequence contains a value.
• in : Returns True if value is in sequence → 'a' in 'apple'
• not in : Returns True if value is not in sequence → 'z' not in 'apple'
7. Identity Operators
Used to compare objects, not values.
• is : Returns True if two variables refer to the same object
• is not : Returns True if they do not refer to the same object
8. Special Cases & Interview Questions
Some tricky scenarios you must know for interviews:
1 What is the difference between '==' and 'is'?
2 Why does 0.1 + 0.2 == 0.3 return False in Python?
3 What happens if you divide by zero? (ZeroDivisionError)
4 How does Python handle very large numbers with ** operator?
5 Explain short-circuiting in logical operators (and/or).
6 Is 'in' operator faster on list or set? Why?