AssertionError
AssertionError: Expected 5, got 3
An assert statement evaluated to False. Assertions are used for debugging and testing — they verify assumptions about your code.
Fix 1: Fix the Condition
# ❌ Assertion fails because condition is wrong
def divide(a, b):
assert b != 0, "Cannot divide by zero"
return a / b
divide(10, 0) # 💥 AssertionError: Cannot divide by zero
# ✅ Handle the case properly
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
Fix 2: Test Assertion Failed
# ❌ Test expects wrong value
def test_add():
assert add(2, 3) == 6 # 💥 Expected 5, not 6
# ✅ Fix the expected value
def test_add():
assert add(2, 3) == 5
Fix 3: Don’t Use Assert for Input Validation
# ❌ Assertions can be disabled with python -O
assert user_input > 0 # Skipped in optimized mode!
# ✅ Use proper validation
if user_input <= 0:
raise ValueError("Input must be positive")
Fix 4: Add Descriptive Messages
# ❌ No message — hard to debug
assert len(items) > 0
# ✅ Add context
assert len(items) > 0, f"Expected items but got empty list"
Fix 5: Type Assertion
# ❌ Wrong type passed
assert isinstance(data, dict), f"Expected dict, got {type(data)}"
# ✅ Fix the caller to pass the right type
# Or use type hints + mypy for compile-time checking
def process(data: dict) -> None:
...