{"record":{"id":"8e1bcdac8e79d87d","repo":"TheAlgorithms/Python","slug":"factorial-recursive-only-accepts-integral-values","errorCode":null,"errorMessage":"factorial_recursive() only accepts integral values","messagePattern":"factorial_recursive\\(\\) only accepts integral values","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/factorial.py","lineNumber":56,"sourceCode":"def factorial_recursive(n: int) -> int:\n    \"\"\"\n    Calculate the factorial of a positive integer\n    https://en.wikipedia.org/wiki/Factorial\n\n    >>> import math\n    >>> all(factorial_recursive(i) == math.factorial(i) for i in range(20))\n    True\n    >>> factorial_recursive(0.1)\n    Traceback (most recent call last):\n        ...\n    ValueError: factorial_recursive() only accepts integral values\n    >>> factorial_recursive(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: factorial_recursive() not defined for negative values\n    \"\"\"\n    if not isinstance(n, int):\n        raise ValueError(\"factorial_recursive() only accepts integral values\")\n    if n < 0:\n        raise ValueError(\"factorial_recursive() not defined for negative values\")\n    return 1 if n in {0, 1} else n * factorial_recursive(n - 1)\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n\n    n = int(input(\"Enter a positive integer: \").strip() or 0)\n    print(f\"factorial{n} is {factorial(n)}\")\n","sourceCodeStart":38,"sourceCodeEnd":69,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/factorial.py#L38-L69","documentation":"Raised by factorial_recursive() in maths/factorial.py when the argument n is not an int (e.g. a float like 0.1, or a string). The function guards its recursive computation with an isinstance(n, int) check because the recursion n * factorial_recursive(n - 1) and the base case n in {0, 1} assume exact integer arithmetic. Note that bool passes this check since bool subclasses int, but any float, even 5.0, is rejected.","triggerScenarios":"Calling factorial_recursive(0.1), factorial_recursive(5.0), factorial_recursive('5'), or passing a numpy float or Decimal value. Any non-int type reaches the `if not isinstance(n, int)` guard and raises ValueError before recursion starts.","commonSituations":"Passing user input parsed as float (float(input(...))), forwarding values from APIs that deserialize numbers as floats, mixing numpy scalar types into pure-Python math helpers, or forgetting that True/False are the only non-int values accepted.","solutions":["Coerce to int before calling: factorial_recursive(int(n)) when you know the value is integral (e.g. int(5.0)).","Validate with isinstance(n, int) at the call site and surface your own error message for non-integral input.","If you need gamma-function behavior for real numbers, use math.gamma(n + 1) instead of this function.","Use math.factorial(n), which raises its own TypeError for non-integers, if you do not need the recursive implementation."],"exampleFix":"# before\nfactorial_recursive(5.0)  # ValueError\n\n# after\nn = 5.0\nif not isinstance(n, int):\n    n = int(n)  # only if known integral\nfactorial_recursive(n)","handlingStrategy":"type-guard","validationCode":"if not isinstance(n, int):\n    if isinstance(n, float) and n.is_integer():\n        n = int(n)\n    else:\n        raise TypeError(f'expected integer, got {type(n).__name__}')\nresult = factorial_recursive(n)","typeGuard":"def is_int_like(value: object) -> bool:\n    return isinstance(value, int) and not isinstance(value, bool) or (\n        isinstance(value, float) and value.is_integer()\n    )","tryCatchPattern":"try:\n    factorial_recursive(n)\nexcept ValueError as exc:\n    raise TypeError(f'bad factorial input {n!r}') from exc","preventionTips":["Parse user input with int(input(...)) rather than float(input(...)).","Convert numpy scalars with int() before passing to pure-Python math helpers.","Remember bool passes the isinstance check; filter it explicitly if undesired."],"tags":["math","factorial","type-error","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}