Cases & Exceptions

4 min read ·

This topic covers all important exceptions, edge cases, and unexpected behaviors related to Python operators. These are situations where operators behave differently than beginners expect and often cause bugs, wrong logic, or interview traps.

What Do We Mean by “Exceptions” in Operators?

Here, exceptions do not only mean runtime errors, but also:
  • Unexpected outputs
  • Tricky behavior
  • Special rules
  • Python-specific shortcuts
  • Cases where operators don’t behave mathematically

1. Division by Zero (Arithmetic Exception)

Raises:

But This Works

Both also raise ZeroDivisionError.

2. Integer Division vs Floor Division (Negative Numbers)

Explanation:
  • Floor division rounds down, not towards zero
This surprises many learners.

3. Modulus with Negative Numbers

Rule:

4. / Always Returns Float

Even though result is whole number, output is:
To get integer:

5. Comparison Between Different Data Types

Valid comparison → returns False
But this raises error:
Reason: Python does not allow ordering between incompatible types.

6. Chained Comparison Trap

This means:
Not:

7. and / or Do NOT Return Boolean Always

Rules:
  • and → returns first falsy or last value
  • or → returns first truthy value

8. Short-Circuiting Skips Errors

No error occurs because second expression is never evaluated.

9. Boolean Arithmetic Exception

Why?
  • True → 1
  • False → 0

10. is vs == (Identity Exception)

Rule:
  • == → value
  • is → memory reference

11. Small Integer Caching Confusion

Small integers may share memory, large ones usually don’t.

12. Dictionary Membership Checks Keys Only

To check values:

13. Bitwise vs Logical Operator Confusion

Bitwise works on bits, logical works on truth values.

14. Operator Precedence Confusion

Always use parentheses:

15. Assignment Inside Conditions (Walrus Exception)

Without walrus:

16. Immutable vs Mutable Operator Side Effects

But:
Lists mutate, tuples create new objects.

17. not Has Lower Precedence Than You Think

Equivalent to:

18. Set Removes Duplicates Automatically

Because:

19. in with Strings vs Lists

Substring vs element check.

20. Assignment Has Lowest Precedence

Equivalent to:

Key Advice

If an expression:
  • Looks confusing
  • Mixes multiple operators
  • Uses and, or, not, is
Always add parentheses.
This topic alone can prevent most beginner and intermediate Python bugs.
Learn Python Cases & Exceptions | Python Course