donnemartin/interactive-coding-challenges · error · TypeError
num cannot be None
Error message
num cannot be None
What it means
Bits.get_next_largest raises TypeError('num cannot be None') when num is None. It computes the next larger integer with the same number of 1 bits, and the bit-counting loops require an actual integer.
Source
Thrown at bit_manipulation/get_next/get_next_solution.ipynb:118
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Bits(object):\n",
"\n",
" def get_next_largest(self, num):\n",
" if num is None:\n",
" raise TypeError('num cannot be None')\n",
" if num <= 0:\n",
" raise ValueError('num cannot be 0 or negative')\n",
" num_ones = 0\n",
" num_zeroes = 0\n",
" num_copy = num\n",
" # We'll look for index, which is the right-most non-trailing zero\n",
" # Count number of zeroes to the right of index\n",
" while num_copy != 0 and num_copy & 1 == 0:\n",
" num_zeroes += 1\n",
" num_copy >>= 1\n",
" # Count number of ones to the right of index\n",
" while num_copy != 0 and num_copy & 1 == 1:\n",
" num_ones += 1\n",
" num_copy >>= 1\n",
" # Determine index and set the bit\n",
" index = num_zeroes + num_ones\n",
" num |= 1 << index\n",
" # Clear all bits to the right of index\n",View on GitHub (pinned to 358f2cc604)
Solutions
- Supply a positive int, e.g. get_next_largest(6)
- Use a safe default: get_next_largest(num if num is not None else 1)
- Guard the data source so num is always set
Example fix
# before
nxt = bits.get_next_largest(data.get('value'))
# after
val = data.get('value')
if val is None:
raise ValueError("'value' missing")
nxt = bits.get_next_largest(val) Defensive patterns
Strategy: validation
Validate before calling
if num is None:
raise ValueError('num is required')
bits.get_next_largest(num) Type guard
def is_positive_int(v) -> bool:
return isinstance(v, int) and not isinstance(v, bool) and v > 0 Try / catch
try:
nxt = bits.get_next_largest(num)
except TypeError:
nxt = None Prevention
- Require the field at parse time (raise on missing key)
- Avoid None defaults for numeric algorithm inputs
- Unit-test boundary values 0 and None at call sites
When it happens
Trigger: Bits().get_next_largest(None), or passing a value from dict.get(), an optional parameter default of None, or an uninitialized variable.
Common situations: Feeding optional config numbers directly into the API; a refactor that made the parameter optional without adding a default at call sites.
Related errors
- Invalid argument: None
- num cannot be None
- Argument cannot be None
- num cannot be None
- number cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/ecd64aca14323244.
Report an issue: GitHub.