donnemartin/interactive-coding-challenges · error · Exception
Invalid value
Error message
Invalid value
What it means
Bit.update_bit raises a generic Exception('Invalid value') when the value parameter is None or not exactly 0 or 1. Bit fields can only be set to a single bit, so any other value is rejected before set_bit/clear_bit is called.
Source
Thrown at bit_manipulation/bit/bit_solution.ipynb:239
" self.number &= mask\n",
" return self.number\n",
"\n",
" @validate_index\n",
" def clear_bits_msb_to_index(self, index):\n",
" mask = (1 << index) - 1\n",
" self.number &= mask\n",
" return self.number\n",
"\n",
" @validate_index\n",
" def clear_bits_index_to_lsb(self, index):\n",
" mask = ~((1 << index + 1) - 1)\n",
" self.number &= mask\n",
" return self.number\n",
"\n",
" @validate_index\n",
" def update_bit(self, index, value):\n",
" if value is None or value not in (0, 1):\n",
" raise Exception('Invalid value')\n",
" if self.get_bit(index) == value:\n",
" return self.number\n",
" if value:\n",
" self.set_bit(index)\n",
" else:\n",
" self.clear_bit(index)\n",
" return self.number"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "code",View on GitHub (pinned to 358f2cc604)
Solutions
- Convert to int explicitly: update_bit(index, int(bool(value)))
- Validate/normalize input to 0 or 1 before the call
- Restructure to use set_bit/clear_bit directly based on a boolean
Example fix
# before bit.update_bit(index, value) # value may be 2/None # after bit.update_bit(index, 1 if value else 0)
Defensive patterns
Strategy: validation
Validate before calling
if value not in (0, 1):
raise ValueError(f'value must be 0 or 1, got {value!r}')
bit.update_bit(index, value) Type guard
def is_bit_value(v) -> bool:
return v in (0, 1) Try / catch
try:
bit.update_bit(index, value)
except Exception as e:
if str(e) == 'Invalid value':
value = int(bool(value))
bit.update_bit(index, value)
else:
raise Prevention
- Normalize booleans to 0/1 before bit APIs
- Validate parsed numeric input against the (0,1) domain
- Prefer set_bit/clear_bit when driving from a boolean
When it happens
Trigger: bit.update_bit(3, 2), bit.update_bit(0, True) (bool is not in (0,1) check? True == 1 so it passes), bit.update_bit(1, None), or passing an int parsed from unvalidated string input like int('5').
Common situations: Passing user-provided or config-driven flag values without normalizing booleans, or mapping textual 'true'/'false' to something other than 0/1.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/c7ae2e9f44b6bc10.
Report an issue: GitHub.