donnemartin/interactive-coding-challenges · error · TypeError

a or b cannot be None

Error message

a or b cannot be None

What it means

Raised by Solution.sum_two (bitwise addition via XOR/carry recursion) when either a or b is None. Both are required for a ^ b and (a & b) << 1; the guard gives a clear message instead of an obscure operand failure.

Source

Thrown at math_probability/sum_two/sum_two_solution.ipynb:122

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "\n",
    "    def sum_two(self, a, b):\n",
    "        if a is None or b is None:\n",
    "            raise TypeError('a or b cannot be None')\n",
    "        result = a ^ b;\n",
    "        carry = (a&b) << 1\n",
    "        if carry != 0:\n",
    "            return self.sum_two(result, carry)\n",
    "        return result;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass two integers
  2. Validate both operands before the call
  3. Sanitize input pairs, replacing or skipping nulls

Example fix

# before
solution.sum_two(a, b)  # b defaults to None

# after
b = 0 if b is None else b
solution.sum_two(a, b)
Defensive patterns

Strategy: validation

Validate before calling

if a is None or b is None: raise ValueError('a and b are required')
solution.sum_two(a, b)

Type guard

def both_ints(*xs): return all(isinstance(x, int) for x in xs)

Try / catch

try:
    solution.sum_two(a, b)
except TypeError as e:
    raise ValueError('invalid operands') from e

Prevention

When it happens

Trigger: Calling sum_two(None, 3) or sum_two(3, None) — commonly from partial argument passing, unpacking records with nulls, or forwarding defaults.

Common situations: Data-driven tests iterating (a, b) pairs that include None; adapters over nullable fields.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/07b7311d631ea732. Report an issue: GitHub.