donnemartin/interactive-coding-challenges · error · TypeError
a or b cannot be None
Error message
a or b cannot be None
What it means
Bits.bits_to_flip raises TypeError when either integer a or b is None. The method counts differing bits (Hamming distance) via a ^ b, which would fail on None, so inputs are validated up front.
Source
Thrown at bit_manipulation/bits_to_flip/bits_to_flip_solution.ipynb:101
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Bits(object):\n",
"\n",
" def bits_to_flip(self, a, b):\n",
" if a is None or b is None:\n",
" raise TypeError('a or b cannot be None')\n",
" count = 0\n",
" c = a ^ b\n",
" while c:\n",
" count += c & 1\n",
" c >>= 1\n",
" return count"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "code",
"execution_count": 2,View on GitHub (pinned to 358f2cc604)
Solutions
- Ensure both arguments are ints before calling; supply defaults (a or 0)
- Add an upstream null check on the data producing a and b
- Catch TypeError if None is a legitimate sentinel you handle elsewhere
Example fix
# before
flips = bits.bits_to_flip(old_flags, new_flags)
# after
if old_flags is None or new_flags is None:
raise ValueError('both flag values are required')
flips = bits.bits_to_flip(old_flags, new_flags) Defensive patterns
Strategy: validation
Validate before calling
if a is None or b is None:
raise ValueError('both a and b are required')
Bits().bits_to_flip(a, b) Type guard
def both_ints(*vals) -> bool:
return all(isinstance(v, int) and not isinstance(v, bool) for v in vals) Try / catch
try:
count = bits.bits_to_flip(a, b)
except TypeError:
count = None # one side missing; skip comparison Prevention
- Use data['key'] instead of data.get('key') for required fields
- Give optional numeric params concrete int defaults
- Validate payloads before comparison logic
When it happens
Trigger: Bits().bits_to_flip(None, 5), bits_to_flip(a, None), or calling with values obtained from optional fields, optional function params, or dict lookups that returned None.
Common situations: Comparing two config versions or flags where one side is missing a key; optional numeric parameters flowing straight into the comparison.
Related errors
- number cannot be None
- Invalid argument: None
- num cannot be None
- num cannot be None
- Argument cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/5c2710502c962b4b.
Report an issue: GitHub.