πŸ”§ Error Fixes
Β· 1 min read

Python AssertionError β€” How to Fix It


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:
    ...

Related: Pip Install Error Fix

πŸ“˜