{"record":{"id":"561b4a84119dbf0e","repo":"TheAlgorithms/Python","slug":"input-must-be-an-integer-561b4a","errorCode":null,"errorMessage":"Input must be an integer","messagePattern":"Input must be an integer","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"maths/number_of_digits.py","lineNumber":26,"sourceCode":"\n    >>> num_digits(12345)\n    5\n    >>> num_digits(123)\n    3\n    >>> num_digits(0)\n    1\n    >>> num_digits(-1)\n    1\n    >>> num_digits(-123456)\n    6\n    >>> num_digits('123')  # Raises a TypeError for non-integer input\n    Traceback (most recent call last):\n        ...\n    TypeError: Input must be an integer\n    \"\"\"\n\n    if not isinstance(n, int):\n        raise TypeError(\"Input must be an integer\")\n\n    digits = 0\n    n = abs(n)\n    while True:\n        n = n // 10\n        digits += 1\n        if n == 0:\n            break\n    return digits\n\n\ndef num_digits_fast(n: int) -> int:\n    \"\"\"\n    Find the number of digits in a number.\n    abs() is used as logarithm for negative numbers is not defined.\n\n    >>> num_digits_fast(12345)\n    5","sourceCodeStart":8,"sourceCodeEnd":44,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/number_of_digits.py#L8-L44","documentation":"Raised by num_digits() in maths/number_of_digits.py when n is not an int. The function counts decimal digits with integer floor-division (n = n // 10), an operation that only terminates correctly for ints; floats, strings, and other types are rejected with TypeError before the loop.","triggerScenarios":"num_digits('123') as in the doctest, num_digits(12.0), num_digits(None), or num_digits(True) (which passes, since bool subclasses int).","commonSituations":"Values from input()/CLI remaining strings, JSON numbers parsed as float, or passing the wrong variable (a label or flag instead of the count).","solutions":["Convert first: num_digits(int(value)).","Use argparse type=int or int(input()) so inputs arrive as ints.","If accepting floats, decide policy (count digits of int part) and convert explicitly: num_digits(int(abs(x)))."],"exampleFix":"# before\nnum_digits('123')\n\n# after\nnum_digits(int('123'))","handlingStrategy":"type-guard","validationCode":"n = int(n)  # raises early with your own context if n is a bad string","typeGuard":"def is_int(x) -> bool:\n    return isinstance(x, int) and not isinstance(x, bool)","tryCatchPattern":null,"preventionTips":["Use argparse type=int for numeric inputs.","Convert JSON/parsed numbers once at the boundary."],"tags":["math","typeerror","type-validation","digits"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}