donnemartin/interactive-coding-challenges · error · TypeError
num cannot be None
Error message
num cannot be None
What it means
Bits.pairwise_swap raises TypeError('num cannot be None') when num is None. The method swaps even and odd bit pairs using fixed 0xAAAA/0x5555 masks and requires an integer operand.
Source
Thrown at bit_manipulation/pairwise_swap/pairwise_swap_solution.ipynb:118
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Bits(object):\n",
"\n",
" def pairwise_swap(self, num):\n",
" if num is None:\n",
" raise TypeError('num cannot be None')\n",
" if num == 0 or num == 1:\n",
" return num\n",
" odd = (num & int('1010101010101010', base=2)) >> 1\n",
" even = (num & int('0101010101010101', base=2)) << 1\n",
" return odd | even"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},View on GitHub (pinned to 358f2cc604)
Solutions
- Pass an int: pairwise_swap(0b1010)
- Default safely: pairwise_swap(num or 0)
- Fix the upstream source of the None value
Example fix
# before
swapped = bits.pairwise_swap(data.get('value'))
# after
value = data.get('value')
if value is None:
raise ValueError("'value' required")
swapped = bits.pairwise_swap(value) Defensive patterns
Strategy: validation
Validate before calling
if num is None:
raise ValueError('num is required')
bits.pairwise_swap(num) Type guard
def is_int(v) -> bool:
return isinstance(v, int) and not isinstance(v, bool) Try / catch
try:
swapped = bits.pairwise_swap(num)
except TypeError:
swapped = None Prevention
- Default numeric params to 0 rather than None
- Check lookups for None before bit operations
- Keep test fixtures fully populated
When it happens
Trigger: Bits().pairwise_swap(None), or passing an optional parameter, a None-returning lookup, or an uninitialized variable.
Common situations: Optional numeric fields flowing into the call; refactor that changed a required parameter to optional; test fixtures missing a value.
Related errors
- Invalid argument: None
- num cannot be None
- num cannot be None
- Argument cannot be None
- number cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/aaaaf403cfd11834.
Report an issue: GitHub.