Mid-level 5 min · March 05, 2026

Python Operators: The `is` vs `==` Gotcha That Costs $5000

Production bug: payments over $5.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • Python operators are symbols that perform operations on values and variables
  • Seven categories: arithmetic, comparison, logical, assignment, identity, membership, bitwise
  • Arithmetic operators include / (float) and // (floor) — mixing them gives different results
  • Comparison operators (== vs =) is the #1 bug: = assigns, == compares
  • Identity operator is checks memory reference, not value — use == for value equality
  • Logical operators short-circuit: and stops at first False, or stops at first True
Plain-English First

Think of a Python operator like the buttons on a calculator. The numbers are your data, and the operator is the instruction that tells Python what to DO with them — add them, compare them, combine them. When you write 10 + 5, the + is the operator: it tells Python 'hey, add these two things together.' Without operators, you'd have data sitting around with no way to actually work with it — like having ingredients but no recipe.

Every program you'll ever write comes down to one thing: making decisions with data. Should this user get a discount? Is this password long enough? How much tax does this order cost? Every single one of those questions is answered using operators. They're the verbs of Python — they make things happen. If variables are the nouns (storing data), operators are what bring that data to life.

Before operators existed as a concept, you'd have to write entire custom functions just to add two numbers or check if one value was greater than another. Operators are shorthand that Python (and every other language) gives you so you can express complex logic in a single, readable character or symbol. They solve the problem of 'how do I actually DO something with my data?'

By the end of this article, you'll be able to use all seven categories of Python operators with confidence — arithmetic, comparison, logical, assignment, identity, membership, and bitwise. You'll know not just how to write them but WHY each one exists and when to reach for it. You'll also know the traps that catch beginners (and sometimes experienced devs), so you can sidestep them from day one.

Arithmetic Operators — Python as Your Calculator

Arithmetic operators are the ones you already know from maths class — addition, subtraction, multiplication, and division. But Python adds a few extras that are genuinely useful in real programming: floor division, modulus, and exponentiation.

Floor division (//) divides two numbers and throws away the decimal, giving you only the whole number part. Think of splitting a pizza: if 7 people share a pizza cut into 2, each person gets 3 slices — the remaining 1 slice doesn't magically split. That leftover is exactly what the modulus operator (%) gives you.

The modulus operator is one of the most underrated tools in programming. It's how you check if a number is even or odd, how you build cycling patterns, and how you keep a counter wrapping around a fixed range. The exponent operator () raises a number to a power — so 2 8 gives you 256, which matters a lot in computing, cryptography, and data sizing.

These seven arithmetic operators cover almost every mathematical operation you'll need in everyday Python programming.

arithmetic_operators.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# ─── Arithmetic Operators in Python ───────────────────────────────────────
# Let's use a real-world scenario: calculating an order total at a bakery.

items_ordered = 7       # Number of croissants ordered
price_per_item = 3.50   # Price in dollars

# Addition: total cost before any extras
subtotal = items_ordered + 2.00  # Adding a $2 bag fee
print("Subtotal with bag fee:", subtotal)  # 9.5

# Subtraction: applying a discount
discount = 1.50
price_after_discount = subtotal - discount
print("After discount:", price_after_discount)  # 8.0

# Multiplication: total cost for the original order
total_cost = items_ordered * price_per_item
print("Total cost:", total_cost)  # 24.5

# Division: splitting the bill evenly among friends
num_friends = 2
cost_per_person = total_cost / num_friends
print("Cost per person:", cost_per_person)  # 12.25

# Floor Division: how many whole boxes of 3 can we fill?
boxes_of_three = items_ordered // 3
print("Full boxes of 3:", boxes_of_three)  # 2  (7 // 3 = 2, ignores remainder)

# Modulus: how many croissants are left over after boxing?
leftover_croissants = items_ordered % 3
print("Leftover croissants:", leftover_croissants)  # 1  (7 % 3 = 1)

# Exponentiation: calculate 2 to the power of 8 (useful in computing)
byte_combinations = 2 ** 8
print("Possible values in one byte:", byte_combinations)  # 256
Output
Subtotal with bag fee: 9.5
After discount: 8.0
Total cost: 24.5
Cost per person: 12.25
Full boxes of 3: 2
Leftover croissants: 1
Possible values in one byte: 256
Pro Tip: Use % to Check Even or Odd
number % 2 == 0 means the number is even. number % 2 == 1 means it's odd. This trick appears in almost every coding interview that involves loops or number patterns — burn it into your memory now.
Production Insight
Division surprises engineers moving from Python 2: 5 / 2 gives 2.5 in Python 3, not 2. Use // when you need whole-number division. Floor division also matters in indexing — negative numbers round down (more negative), so (-7) // 3 gives -3, not -2. Always test boundary cases.
In financial systems, avoid floating-point for currency — use Decimal from the decimal module. 0.1 + 0.2 is 0.30000000000000004 because of IEEE 754 representation. This is not a Python bug; it's how every CPU works.
Key Takeaway
/ always returns a float; // truncates toward negative infinity; % gives the remainder with the sign of the divisor.
Use Decimal for money — floats will cost you real dollars.

Comparison and Logical Operators — Teaching Python to Make Decisions

Comparison operators answer a yes-or-no question about your data. Is this value bigger than that one? Are these two values equal? Python evaluates the comparison and hands you back a boolean — either True or False. That True or False is then used by if-statements, while-loops, and everywhere else decisions are made.

There are six comparison operators: equal (==), not equal (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Notice that equality uses TWO equals signs (==). One equals sign (=) is assignment — it stores a value. Two equals signs (==) is comparison — it asks a question.

Logical operators — and, or, not — let you combine multiple comparisons into a single, more powerful condition. Think of them like the connectors in everyday language. 'I'll go to the party IF it's on Saturday AND I'm not working.' That AND is exactly what Python's and operator does: both conditions must be True for the whole thing to be True.

or means at least one condition must be True. not flips a boolean — True becomes False and False becomes True. Together, these six comparison operators and three logical operators are the backbone of every conditional statement you'll ever write.

comparison_logical_operators.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# ─── Comparison and Logical Operators ─────────────────────────────────────
# Scenario: A simple age-gate for a website with a premium tier.

user_age = 22
user_is_subscriber = True
minimum_age = 18
subscription_price = 9.99
account_balance = 15.00

# ── Comparison Operators ──────────────────────────────────────────────────

# == checks equality (note: NOT a single = which would assign a value)
print(user_age == 22)        # True  — age IS 22
print(user_age == 30)        # False — age is NOT 30

# != checks inequality
print(user_age != 30)        # True  — 22 is not 30

# > and < check magnitude
print(user_age > minimum_age)   # True  — 22 is greater than 18
print(user_age < minimum_age)   # False — 22 is not less than 18

# >= and <= include the boundary value
print(user_age >= 22)        # True  — 22 is equal to 22, so >= is satisfied
print(user_age <= 21)        # False — 22 is not less than or equal to 21

# ── Logical Operators ─────────────────────────────────────────────────────

# AND: BOTH conditions must be True
can_access_premium = user_age >= minimum_age and user_is_subscriber
print("Can access premium:", can_access_premium)  # True (22>=18 AND subscriber)

# OR: AT LEAST ONE condition must be True
can_afford_subscription = account_balance >= subscription_price or user_is_subscriber
print("Can afford subscription:", can_afford_subscription)  # True

# NOT: flips the boolean — True becomes False, False becomes True
print("Is a guest user:", not user_is_subscriber)  # False (they ARE a subscriber)

# Combining all three for a real access check
user_is_banned = False
full_access = (user_age >= minimum_age) and user_is_subscriber and (not user_is_banned)
print("Full access granted:", full_access)  # True
Output
True
False
True
True
False
True
False
Can access premium: True
Can afford subscription: True
Is a guest user: False
Full access granted: True
Watch Out: = vs == Is the #1 Beginner Bug
Writing if user_age = 18 instead of if user_age == 18 is a SyntaxError in Python. A single = assigns a value. Two == compares values. If your if-statement is throwing a SyntaxError and you can't see why, check your equals signs first — every time.
Production Insight
Short-circuit evaluation can mask bugs. In if user and user.is_active(), if user is None, Python never calls is_active(). That's good. But in if user.is_active() and user, you get AttributeError before the short-circuit can save you. Always put the cheap or guard check first.
and and or don't return True/False — they return one of the operands. 0 or [] returns [], which is falsy. This trips up new devs when the result is used directly in a boolean context. Wrap with bool() if you need a strict boolean.
Key Takeaway
Short-circuit avoids errors but also hides them — guard conditions go first.
and/or return operands, not booleans. If you need True/False, use bool() explicitly.

Assignment Operators — Updating Values Without Repeating Yourself

You already know the basic assignment operator: the single equals sign (=). It stores a value into a variable. But Python gives you a set of shorthand assignment operators that combine assignment with an arithmetic operation in one step. These are called compound assignment operators, and they exist purely to save you from writing repetitive code.

Instead of writing score = score + 10, you can write score += 10. Python reads this as 'take the current value of score, add 10 to it, and store the result back in score.' Same result, less noise. Every arithmetic operator has a compound version: +=, -=, =, /=, //=, %=, and *=.

These aren't just cosmetic shortcuts. In long functions or loops, compound assignment operators make your code significantly easier to read because the variable name only appears once per line. Your eye immediately knows the variable is being updated, not reassigned from scratch. You'll see these constantly in real-world Python code, especially in loops that accumulate totals, counts, or running scores.

assignment_operators.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# ─── Assignment Operators ─────────────────────────────────────────────────
# Scenario: Tracking a player's score in a simple game loop.

player_score = 0         # Basic assignment: store 0 in player_score
player_lives = 3
boss_health = 100

# += adds the right value to the variable and saves the result
player_score += 50       # Player collected a coin: score is now 50
player_score += 100      # Player defeated an enemy: score is now 150
print("Score after two events:", player_score)  # 150

# -= subtracts from the variable
player_lives -= 1        # Player hit a spike: lives drop from 3 to 2
print("Lives remaining:", player_lives)  # 2

# *= multiplies the variable by a value
player_score *= 2        # Double score power-up activated!
print("Score after double power-up:", player_score)  # 300

# /= divides the variable (result is always a float)
boss_health /= 2         # Boss hit by a special attack — half health
print("Boss health:", boss_health)  # 50.0  ← notice the .0, it becomes a float

# //= floor-divides the variable (result stays a whole number)
boss_health = 100        # Reset boss health for demo
boss_health //= 3        # Each hit removes a third (rounded down)
print("Boss health after floor division:", boss_health)  # 33

# %= stores the remainder
ammo_count = 17
shots_per_clip = 5
remainder_in_clip = ammo_count % 5  # How many bullets are in the partial clip?
ammo_count %= 5          # ammo_count now holds only the leftover
print("Bullets in partial clip:", ammo_count)  # 2

# **= raises the variable to a power
base_damage = 2
base_damage **= 4        # Damage scales exponentially: 2^4
print("Scaled damage:", base_damage)  # 16
Output
Score after two events: 150
Lives remaining: 2
Score after double power-up: 300
Boss health: 50.0
Boss health after floor division: 33
Bullets in partial clip: 2
Scaled damage: 16
Good to Know: /= Always Returns a Float
Even if both numbers divide perfectly (like 10 /= 2), the result is 5.0, not 5. Python's regular division always produces a float. If you need a whole number result, use //= (floor division assignment) instead.
Production Insight
Compound assignment operators are not atomic. amount -= 1 in a multithreaded context can race — two threads may both read the same value and write back the same decremented result, losing a decrement. Use threading.Lock or an atomic type from multiprocessing.sharedctypes if you need thread-safe increments.
Walrus operator := is not compound assignment — it assigns and returns in the same expression. `if (x := get_data()) is None:` is a common pattern but can reduce readability when overused.
Key Takeaway
Compound assignment operators shorten code but are non-atomic — not safe for concurrent updates.
/= always produces a float; use //= for integer division in-place.

Identity, Membership and Bitwise Operators — The Powerful Trio Beginners Skip

Most beginners learn arithmetic and comparison operators and stop there. But three more categories show up constantly in real Python code, and skipping them will leave you confused when you read someone else's code.

Identity operators (is and is not) check whether two variables point to the exact same object in memory — not just whether they have equal values. This is subtle but critical. Two variables can hold the same value but be completely different objects. Use == to compare values. Use is to check if something is literally None.

Membership operators (in and not in) check whether a value exists inside a collection like a list, string, or dictionary. They read almost like plain English: if 'admin' in user_roles is as clear as code gets. You'll use these constantly when filtering data or validating input.

Bitwise operators work on the individual binary digits (bits) of integers. They look strange at first but they're essential for low-level tasks like setting feature flags, working with permissions, or processing binary data. You won't need them every day, but you absolutely need to recognise them.

identity_membership_bitwise.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# ─── Identity, Membership, and Bitwise Operators ──────────────────────────

# ── IDENTITY OPERATORS: is, is not ───────────────────────────────────────
# 'is' checks if two names point to the SAME object in memory
# '==' checks if two objects have the SAME VALUE

response_data = None

# The correct way to check for None is always 'is', not '=='
if response_data is None:
    print("No data received from the server.")  # This prints

# Demonstrating the difference between 'is' and '=='
list_a = [1, 2, 3]
list_b = [1, 2, 3]   # Same values, but a brand-new list object in memory
list_c = list_a      # list_c points to the SAME object as list_a

print(list_a == list_b)   # True  — values are identical
print(list_a is list_b)   # False — they are different objects in memory
print(list_a is list_c)   # True  — both names point to the same object

# ── MEMBERSHIP OPERATORS: in, not in ─────────────────────────────────────
# Check if a value exists inside a collection

allowed_file_types = ['jpg', 'png', 'gif', 'webp']
uploaded_extension = 'pdf'

if uploaded_extension not in allowed_file_types:
    print(f".{uploaded_extension} files are not allowed.")  # This prints

welcome_message = "Welcome to TheCodeForge!"
if "CodeForge" in welcome_message:
    print("Brand name found in message.")  # This prints

# ── BITWISE OPERATORS ─────────────────────────────────────────────────────
# These operate on binary representations of integers.
# Practical use: combining permission flags (like Linux file permissions)

READ_PERMISSION    = 0b100   # Binary 4:  the 'read' bit is ON
WRITE_PERMISSION   = 0b010   # Binary 2:  the 'write' bit is ON
EXECUTE_PERMISSION = 0b001   # Binary 1:  the 'execute' bit is ON

# & (AND): both bits must be 1 — used to CHECK if a permission is set
# | (OR):  at least one bit is 1 — used to COMBINE permissions
# ~ (NOT): flips all bits
# ^ (XOR): bits differ — used to TOGGLE a permission
# << (left shift): multiply by powers of 2
# >> (right shift): divide by powers of 2

# Grant read and write permissions using OR
user_permissions = READ_PERMISSION | WRITE_PERMISSION
print("User permissions (binary):", bin(user_permissions))  # 0b110  (decimal 6)

# Check if user has WRITE permission using AND
has_write = user_permissions & WRITE_PERMISSION
print("Has write access:", bool(has_write))  # True

# Check if user has EXECUTE permission
has_execute = user_permissions & EXECUTE_PERMISSION
print("Has execute access:", bool(has_execute))  # False

# Left shift: quick multiply by 2
base_value = 3
print("3 left-shifted by 2:", base_value << 2)   # 12  (3 * 4)

# Right shift: quick divide by 2
print("12 right-shifted by 2:", 12 >> 2)          # 3   (12 / 4)
Output
No data received from the server.
True
False
True
.pdf files are not allowed.
Brand name found in message.
User permissions (binary): 0b110
Has write access: True
Has execute access: False
3 left-shifted by 2: 12
12 right-shifted by 2: 3
Watch Out: Never Use == to Check for None
Always write if value is None, never if value == None. Why? A custom class can override the == operator to return True even when it isn't None, silently breaking your logic. The is operator cannot be overridden — it always checks raw memory identity. This is a PEP 8 rule and an interview favourite.
Production Insight
Bitwise & vs logical and is a common confusion: 3 & 5 is 1 (bitwise), while 3 and 5 is 5 (logical, returning the last truthy operand). Using & for logical checks can produce silent data bugs — if permissions & 4: is a common bit test, but if permissions and 4: behaves completely differently.
Membership in for dictionaries checks keys, not values. 'key' in dict is O(1); 'value' in dict.values() is O(n). Choose wisely in performance-critical paths.
Key Takeaway
is checks identity — use it only for None and singletons. == checks value — use that for everything else.
in on a dict checks keys, not values. For bit manipulation, use &, |, ^ — never and/or.

Operator Precedence and Associativity — The Silent Bug That Changes Your Results

When you write an expression with multiple operators, Python doesn't just evaluate left to right. It follows a strict order called operator precedence. This is the same PEMDAS you learned in school, but expanded to cover all operators.

Multiplication and division happen before addition and subtraction. 2 + 3 4 gives 14, not 20. Comparison operators (==, <, >) have lower precedence than arithmetic, so 3 + 4 > 2 3 is evaluated as (3 + 4) > (2 * 3), which is 7 > 6, True.

Logical operators have their own precedence: not > and > or. So not True or True and False is actually (not True) or (True and False), which is False or False, giving False. That's probably not what you meant. The safest rule: use parentheses when mixing logical or arithmetic operators. They cost nothing and prevent bugs.

Associativity determines the order when operators have the same precedence. Most operators are left-associative (evaluate left to right), but assignment and exponentiation are right-associative. a = b = c means a = (b = c). 2 3 2 is 2 (3 2) = 2 9 = 512, not (2 3) ** 2 = 64.

operator_precedence.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# ─── Operator Precedence and Associativity ────────────────────────────────

# Example 1: Arithmetic precedence
result_1 = 2 + 3 * 4
print("2 + 3 * 4 =", result_1)  # 14 (NOT 20)

result_2 = (2 + 3) * 4
print("(2 + 3) * 4 =", result_2)  # 20

# Example 2: Comparison vs arithmetic
result_3 = 3 + 4 > 2 * 3
print("3 + 4 > 2 * 3 =", result_3)  # True (7 > 6)

# Example 3: Logical precedence
result_4 = not True or True and False
print("not True or True and False =", result_4)  # False
# Equivalent to: (not True) or (True and False) = False or False = False

result_5 = (not True) or (True and False)
print("Same with parentheses:", result_5)  # False

# Without parentheses, it's easy to misread:
# Suppose you wanted: not (True or True) and False
result_6 = not (True or True) and False
print("not (True or True) and False =", result_6)  # False (and False anyway)

# Example 4: Right-associative exponentiation
result_7 = 2 ** 3 ** 2
print("2 ** 3 ** 2 =", result_7)  # 512  (2**(3**2) = 2**9)

result_8 = (2 ** 3) ** 2
print("(2 ** 3) ** 2 =", result_8)  # 64  (8**2)

# Example 5: Assignment is right-associative
a = b = c = 5
print("a =", a, "b =", b, "c =", c)  # All 5: a = (b = (c = 5))

# Example 6: Common real-world mistake
hours = 8
rate = 15
# You want: (hours * rate) * 1.1 with 10% bonus
# But what if you forget parentheses?
total = hours * rate + 0.1
print("Wrong total:", total)  # 120.1 (because + has lower precedence)
total_correct = hours * rate + (hours * rate * 0.1)
print("Correct total:", total_correct)  # 132.0
Output
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
3 + 4 > 2 * 3 = True
not True or True and False = False
Same with parentheses: False
not (True or True) and False = False
2 ** 3 ** 2 = 512
(2 ** 3) ** 2 = 64
a = 5 b = 5 c = 5
Wrong total: 120.1
Correct total: 132.0
PEMDAS+ — The Full Precedence Mental Model
  • Exponentiation (**) is highest among arithmetic operators and right-associative
  • Multiplication, division, floor division, modulus (*, /, //, %) come before addition and subtraction
  • Bitwise shifts (<<, >>) come after addition but before comparison
  • Comparison operators (==, !=, <, >, <=, >=) come after arithmetic and bitwise shifts
  • Logical not comes after comparison, and + or come after that
  • Assignment (=, +=, etc.) is lowest — it happens last
Production Insight
A real-world failure: a pricing system computed price = base tax + discount but intended base (tax + discount). The bug caused $50,000 in undercharged orders over 3 months because no one noticed the discount was being added after tax instead of before.
Parentheses are not just for safety — they are documentation. If a future engineer reads your code, they understand your intent without memorising precedence tables. Linters like flake8 and pylint can warn about unnecessary parentheses, but for logical/bitwise mixes, keep them.
Key Takeaway
Precedence is not intuitive — multiply/divide before add/subtract, comparisons after arithmetic, logical operators last.
Always parenthesize complex expressions. It's not weak code, it's clear intent.
● Production incidentPOST-MORTEMseverity: high

The $5000 Integer Cache Bug: When `is` Broke Our Payment Validation

Symptom
Payments over $5.12 were randomly flagged as invalid, but the same amount would work on retry. No consistent pattern, no exceptions in logs.
Assumption
The developer assumed is and == are interchangeable for integer comparisons, as they had read that Python caches small integers.
Root cause
Python caches integers only in the range [-5, 256]. For amounts like 5.12 (float) or integers >256, is checks identity — and each arithmetic operation creates a new object. So amount is THRESHOLD was False even though the values matched.
Fix
Replace if payment.amount is cached_threshold: with if payment.amount == cached_threshold:.
Key lesson
  • Never use is for value comparison — it checks memory identity, not equality.
  • == is always safe for comparing primitive values and most objects.
  • Python's integer cache is an implementation detail, not a contract.
Production debug guideHow to identify and fix common operator bugs without restarting your service4 entries
Symptom · 01
Boolean condition behaves unexpectedly — sometimes True, sometimes False
Fix
Add debug prints: print(type(x), repr(x), bool(x)) before the condition. Check for truthiness pitfalls: 0, empty strings, and None all evaluate to False.
Symptom · 02
Arithmetic result is a float when you expected an int (or vice versa)
Fix
Verify all operators in the expression. The / always returns a float; use // for integer division. Check operand types with type().
Symptom · 03
Membership check fails even though the value appears in the collection
Fix
Print the collection and the value: print(repr(collection), repr(value)). Check for type mismatches: '123' in [123] is False. Also check for mutable objects in sets/dicts.
Symptom · 04
Logical and / or returns something unexpected (not boolean)
Fix
Remember and and or return the last evaluated operand, not necessarily True/False. Use bool() to cast if you need a boolean.
All Python Operators at a Glance
Operator CategorySymbolsReturnsTypical Use Case
Arithmetic+ - / // % *Number (int or float)Maths calculations, price totals, loop counters
Comparison== != > < >= <=Boolean (True/False)Conditions in if-statements and while-loops
Logicaland or notBoolean or last operandCombining multiple conditions, short-circuit guards
Assignment= += -= = /= //= %= *=Updated variable valueUpdating running totals, scores, counters in loops
Identityis is notBoolean (True/False)Checking if a variable is None or points to same object
Membershipin not inBoolean (True/False)Checking if a value exists in a list, string, or dict
Bitwise& | ~ ^ << >>IntegerPermission flags, binary data, low-level optimisation

Key takeaways

1
Single = assigns, double == compares. This is the #1 Python bug
it causes a SyntaxError every time.
2
/ always returns a float; // floors towards negative infinity. Use // for integer division and / when you need a decimal.
3
% gives remainder
perfect for even/odd checks, circular buffers, and wrapping counters.
4
Always use is to check for None
it cannot be overridden. Use == for everything else.
5
Logical and/or short-circuit and return the last evaluated operand
not necessarily a boolean.
6
Parentheses are free
use them whenever mixing arithmetic, comparison, or logical operators to make precedence explicit.

Common mistakes to avoid

4 patterns
×

Using = instead of == in a condition (Assignment instead of Comparison)

Symptom
SyntaxError: invalid syntax on your if-statement line. Python refuses to run the code.
Fix
Always use == for comparison. Remember: = stores a value, == asks a question. If you're checking equality, you need two equals signs.
×

Using == to compare with None instead of 'is'

Symptom
Code works most of the time but silently fails with custom objects that override __eq__. The condition may return True when it shouldn't.
Fix
Always write 'if variable is None' or 'if variable is not None'. The 'is' operator checks memory identity, which is the only reliable way to check for None.
×

Expecting integer division from '/' (forward slash)

Symptom
7 / 2 returns 2.5 when you expected 3. Array indices or loop limits break because the result is a float.
Fix
Use // (floor division) when you need a whole-number result. The single / always returns a float in Python 3. This catches developers coming from Python 2, where / between two integers returned an integer.
×

Using 'and'/'or' where you meant &/| (logical vs bitwise)

Symptom
Condition returns unexpected True/False. For example, evaluating permissions: 'if permissions and 4' always True if permissions non-zero, instead of checking the bit.
Fix
Use bitwise operators (&, |, ^) for bit manipulation. Use logical operators (and, or) for boolean logic. Never mix them without parentheses.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is the difference between the == operator and the is operator in Py...
Q02JUNIOR
What does the modulus operator (%) actually do, and give two practical p...
Q03JUNIOR
Explain operator precedence in Python. What is the value of `2 + 3 * 4` ...
Q04SENIOR
What does the walrus operator (:=) do in Python 3.8+? Give a real-world ...
Q01 of 04JUNIOR

What is the difference between the == operator and the is operator in Python? Give an example where they produce different results.

ANSWER
== compares values (the contents of objects), while is compares identities (memory addresses). They differ when two objects have the same value but are different objects. Example: ``python a = [1, 2, 3] b = [1, 2, 3] print(a == b) # True because values match print(a is b) # False because they are two separate list objects ` Note that Python caches small integers (-5 to 256), but this is an implementation detail. Never rely on it. Always use is for None and True/False singletons, and ==` for value comparisons.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
How many types of operators are there in Python?
02
What is operator precedence in Python and why does it matter?
03
What is the difference between / and // in Python?
04
Can you chain comparison operators in Python?
05
What is the difference between 'and' and '&' in Python?
🔥

That's Python Basics. Mark it forged?

5 min read · try the examples if you haven't

Previous
Variables in Python
5 / 17 · Python Basics
Next
Input and Output in Python