TheAlgorithms/Python · error · ValueError

n must be an integer

Error message

n must be an integer

What it means

Raised by compute_nums() in project_euler/problem_046/sol1.py when n is not an int instance. The function uses isinstance(n, int) strictly, so floats (including whole floats like 10.0), strings, and None all fail, even if they look numeric. Note the exception type is ValueError even though it signals a type problem.

Source

Thrown at project_euler/problem_046/sol1.py:90

    [5777]
    >>> compute_nums(2)
    [5777, 5993]
    >>> compute_nums(0)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0
    >>> compute_nums("a")
    Traceback (most recent call last):
        ...
    ValueError: n must be an integer
    >>> compute_nums(1.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be an integer

    """
    if not isinstance(n, int):
        raise ValueError("n must be an integer")
    if n <= 0:
        raise ValueError("n must be >= 0")

    list_nums = []
    for num in range(len(odd_composites)):
        i = 0
        while 2 * i * i <= odd_composites[num]:
            rem = odd_composites[num] - 2 * i * i
            if is_prime(rem):
                break
            i += 1
        else:
            list_nums.append(odd_composites[num])
            if len(list_nums) == n:
                return list_nums

    return []

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a plain int: compute_nums(2).
  2. Coerce near the call site: compute_nums(int(user_value)) after confirming the value is numeric.
  3. For numpy types, convert explicitly: compute_nums(int(np_value)).
  4. If you control the caller chain, keep n as int end-to-end instead of float intermediate values.

Example fix

# before
n = json.loads('{"count": 2.0}')" "["count"]
compute_nums(n)  # ValueError: n must be an integer

# after
n = int(json.loads('{"count": 2.0}')" "["count"])
compute_nums(n)
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(n, int) or isinstance(n, bool):
    raise TypeError(f"n must be int, got {type(n).__name__}")
compute_nums(n)

Type guard

def is_plain_int(value) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)

Try / catch

try:
    compute_nums(n)
except ValueError as e:
    if "must be an integer" in str(e):
        n = int(float(n))  # only if n was numeric
        compute_nums(n)
    else:
        raise

Prevention

When it happens

Trigger: compute_nums("5"), compute_nums(1.1), compute_nums(10.0), compute_nums(None), or compute_nums(numpy.int64(5)) on some builds where the value is not a plain int. Booleans pass because bool subclasses int.

Common situations: JSON-parsed arguments (json.loads yields floats for numbers like 1.0); CLI args passed as strings; numpy or pandas integer types flowing into the function; division results (e.g. n = len(x)/2) that are floats.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/cf727852da0d19d9. Report an issue: GitHub.