donnemartin/interactive-coding-challenges · error · TypeError
n cannot be None
Error message
n cannot be None
What it means
Raised by Solution.is_power_of_two when n is None. The bit trick n & (n - 1) requires an integer; None would fail with a less clear TypeError, so the method enforces its contract explicitly.
Source
Thrown at math_probability/power_two/power_two_solution.ipynb:108
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def is_power_of_two(self, n):\n",
" if n is None:\n",
" raise TypeError('n cannot be None')\n",
" if n <= 0:\n",
" return False\n",
" return (n & (n - 1)) == 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{View on GitHub (pinned to 358f2cc604)
Solutions
- Pass an integer: is_power_of_two(64)
- Check for None at the call site and default or skip
- Fix the upstream producer returning None
Example fix
# before
solution.is_power_of_two(nums.get(i)) # None when i missing
# after
n = nums.get(i)
if n is not None:
solution.is_power_of_two(n) Defensive patterns
Strategy: type-guard
Validate before calling
if n is None: return False solution.is_power_of_two(n)
Type guard
def is_int(n): return isinstance(n, int)
Try / catch
try:
solution.is_power_of_two(n)
except TypeError:
result = False Prevention
- Default numeric params to 0/sentinel, not None
- Check lookups returned a value before use
When it happens
Trigger: Calling is_power_of_two(None) — an unset variable, a None default, or a value from a lookup that missed (dict.get, next(iter, None)).
Common situations: Interview test harnesses hitting edge cases; passing optional config flags through without defaults.
Related errors
- a or b cannot be None
- a or b cannot be None
- Invalid argument: None
- num cannot be None
- num cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/e7d85cdcc08a8b89.
Report an issue: GitHub.