TheAlgorithms/Python · error · TypeError
Input must be an integer
Error message
Input must be an integer
What it means
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.
Source
Thrown at maths/number_of_digits.py:26
>>> num_digits(12345)
5
>>> num_digits(123)
3
>>> num_digits(0)
1
>>> num_digits(-1)
1
>>> num_digits(-123456)
6
>>> num_digits('123') # Raises a TypeError for non-integer input
Traceback (most recent call last):
...
TypeError: Input must be an integer
"""
if not isinstance(n, int):
raise TypeError("Input must be an integer")
digits = 0
n = abs(n)
while True:
n = n // 10
digits += 1
if n == 0:
break
return digits
def num_digits_fast(n: int) -> int:
"""
Find the number of digits in a number.
abs() is used as logarithm for negative numbers is not defined.
>>> num_digits_fast(12345)
5View on GitHub (pinned to f5988cc097)
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))).
Example fix
# before
num_digits('123')
# after
num_digits(int('123')) Defensive patterns
Strategy: type-guard
Validate before calling
n = int(n) # raises early with your own context if n is a bad string
Type guard
def is_int(x) -> bool:
return isinstance(x, int) and not isinstance(x, bool) Prevention
- Use argparse type=int for numeric inputs.
- Convert JSON/parsed numbers once at the boundary.
When it happens
Trigger: num_digits('123') as in the doctest, num_digits(12.0), num_digits(None), or num_digits(True) (which passes, since bool subclasses int).
Common situations: Values from input()/CLI remaining strings, JSON numbers parsed as float, or passing the wrong variable (a label or flag instead of the count).
Related errors
- Expected a list of numbers as input, found {type(item).__nam
- Expected a list of numbers as input, found {type(point).__na
- Input value must be a positive integer
- Input value must be a 'int' type
- Input must be an integer
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/561b4a84119dbf0e.
Report an issue: GitHub.