donnemartin/interactive-coding-challenges · error · TypeError
a or b cannot be None
Error message
a or b cannot be None
What it means
sum_two implements addition with bitwise operators (XOR plus shifted carry, recursing until carry is 0) and raises TypeError when a or b is None. The guard protects the public API since the internal recursion always passes ints. Without it, a ^ b on None would raise a confusing TypeError about unsupported operand types.
Source
Thrown at online_judges/sum_two/sum_two_solution.ipynb:126
},
{
"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
- Pass non-negative ints, converting explicitly beforehand
- Resolve None-defaults at the call site: b = b if b is not None else 0
- Replace with a + b for production use; the bitwise version is an interview exercise
Example fix
// before
def add(x, y=None):
return sol.sum_two(x, y)
// after
def add(x, y=0):
return sol.sum_two(x, y) Defensive patterns
Strategy: type-guard
Validate before calling
a = a if a is not None else 0 b = b if b is not None else 0 sol.sum_two(a, b)
Type guard
def is_nonneg_int(x):
return isinstance(x, int) and not isinstance(x, bool) and x >= 0 Try / catch
try:
sol.sum_two(a, b)
except TypeError as e:
if 'a or b cannot be None' in str(e):
raise ValueError('operands must be provided') from e
raise Prevention
- Use 0 defaults for numeric optional params
- Validate deserialized numeric fields before calling
- Avoid negative operands with the bitwise carry loop; use '+' instead
When it happens
Trigger: Calling Solution().sum_two(None, 3) or sum_two(3, None); forwarding optional numeric params (e.g. defaults of None) directly into the method.
Common situations: Optional fields in deserialized data left as None and passed through; misreading the API as accepting nullable numbers; notebook cells referencing unassigned variables. Beware also that with negative ints this carry loop can recurse very long in Python (no fixed-width wrap).
Related errors
- a or b cannot be None
- a or b cannot be None
- a or b cannot be None
- Cannot have a None input
- array cannot be None or empty
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/8420128da34542f4.
Report an issue: GitHub.