donnemartin/interactive-coding-challenges · error · TypeError

num cannot be None

Error message

num cannot be None

What it means

Raised by Math.check_prime when num is None. The primality loop compares num < 2 and computes num % i, which would crash on None; the guard converts that into a clear, intentional TypeError at the API boundary.

Source

Thrown at math_probability/check_prime/check_prime_solution.ipynb:97

   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "\n",
    "class Math(object):\n",
    "\n",
    "    def check_prime(self, num):\n",
    "        if num is None:\n",
    "            raise TypeError('num cannot be None')\n",
    "        if num < 2:\n",
    "            return False\n",
    "        for i in range(2, num):\n",
    "            if num % i == 0:\n",
    "                return False\n",
    "        return True\n",
    "\n",
    "    def check_prime_optimized(self, num):\n",
    "        if num is None:\n",
    "            raise TypeError('num cannot be None')\n",
    "        if num < 2:\n",
    "            return False\n",
    "        for i in range(2, int(math.sqrt(num)+1)):\n",
    "            if num % i == 0:\n",
    "                return False\n",
    "        return True"
   ]
  },

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass an integer: check_prime(29)
  2. Guard the call site: if num is not None: math.check_prime(num)
  3. Trace and fix the producer of the None value

Example fix

# before
math.check_prime(numbers.get(key))  # get returns None if missing

# after
value = numbers.get(key)
if value is None:
    raise KeyError(key)
math.check_prime(value)
Defensive patterns

Strategy: type-guard

Validate before calling

if num is None: raise ValueError('num is required')
math.check_prime(num)

Type guard

def is_int(n): return isinstance(n, int)

Try / catch

try:
    math.check_prime(num)
except TypeError as e:
    # handle missing input
    pass

Prevention

When it happens

Trigger: Calling Math().check_prime(None), typically from an uninitialized variable, an optional argument, or a value fetched with dict.get()/list.pop() from an empty collection.

Common situations: Unit tests covering the None edge case; pipelines where the input number comes from an external source (file, API) that can yield None.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/ccdbf1f0993ae8c2. Report an issue: GitHub.