Beginner
Operators in Python
📂 Phase 1: Python Basics, Variables, Data Types (Days 1–5) · Python ProgrammingOperators let you perform calculations, comparisons, and logical checks on values. Python groups them into several families, and a few behave subtly differently from what you might expect coming from another language.
Arithmetic Operators
a = 10
b = 3
print(a + b) # 13 — addition
print(a - b) # 7 — subtraction
print(a * b) # 30 — multiplication
print(a / b) # 3.333... — division ALWAYS returns a float
print(a // b) # 3 — floor division, drops the decimal
print(a % b) # 1 — modulus (remainder)
print(a ** b) # 1000 — exponentiation (10 to the power of 3)
Unlike Java, the / operator in Python always produces a float result, even when dividing two integers evenly (10 / 2 gives 5.0, not 5). Use // specifically when you need integer (floor) division.
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | 5 == 5 → True |
| != | Not equal to | 5 != 3 → True |
| > < | Greater / less than | 5 > 3 → True |
| >= <= | Greater/less than or equal | 5 >= 5 → True |
Logical Operators
age = 20
has_id = True
print(age >= 18 and has_id) # True — both conditions must be true
print(age < 18 or has_id) # True — at least one condition is true
print(not has_id) # False — flips the boolean
Python uses the words and, or, not — not &&, ||, ! like Java or C. Using && in Python raises a SyntaxError.
Assignment Operators
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x //= 4 # x = x // 4 → 6
Identity Operators: is vs ==
This is one of the most frequently confused pairs for beginners coming from another language.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True — same VALUES
print(a is b) # False — different objects in memory
c = a
print(a is c) # True — c points to the exact same object as a
| Operator | Checks |
|---|---|
| == | Whether the values are equal |
| is | Whether both variables point to the exact same object in memory |
Membership Operators: in and not in
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("mango" not in fruits) # True
Interview tip: A classic trick question is "What does == versus is check for small integers?" — due to an internal CPython optimization called integer interning, small integers (typically -5 to 256) are cached and reused, so a is b can return True for small ints even without explicit assignment from one to the other. Never rely on is for value comparisons — always use == for that.