TheAlgorithms/Python · error · ValueError

Invalid input

Error message

Invalid input

What it means

Raised by solution() in project_euler/problem_097/sol1.py when n is not an int or is negative. n selects how many last digits to keep via modulus = 10**n, so it must be a non-negative integer; a single combined isinstance-and-range check rejects floats, strings, and negatives alike with the generic message 'Invalid input'.

Source

Thrown at project_euler/problem_097/sol1.py:36

    >>> solution(8)
    '39992577'
    >>> solution(1)
    '7'
    >>> solution(-1)
    Traceback (most recent call last):
        ...
    ValueError: Invalid input
    >>> solution(8.3)
    Traceback (most recent call last):
        ...
    ValueError: Invalid input
    >>> solution("a")
    Traceback (most recent call last):
        ...
    ValueError: Invalid input
    """
    if not isinstance(n, int) or n < 0:
        raise ValueError("Invalid input")
    modulus = 10**n
    number = 28433 * (pow(2, 7830457, modulus)) + 1
    return str(number % modulus)


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    print(f"{solution(10) = }")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a plain non-negative int: solution(10).
  2. Use argparse with type=int for the digits parameter.
  3. Coerce integral floats before calling: solution(int(n)) when float(n).is_integer().
  4. Because the message is generic, log the offending value yourself when validating.

Example fix

# before
n = float(digits_arg)  # e.g. 10.0 from JSON
last = solution(n)  # ValueError: Invalid input

# after
n = int(digits_arg)
last = solution(n)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or isinstance(n, bool) or n < 0:
    raise ValueError(f"n must be a non-negative int, got {n!r}")
solution(n)

Type guard

def is_valid_digit_count(value) -> bool:
    return isinstance(value, int) and not isinstance(value, bool) and value >= 0

Try / catch

try:
    tail = solution(n)
except ValueError:
    # generic message; re-raise with context
    raise ValueError(f"invalid digit count: {n!r}") from None

Prevention

When it happens

Trigger: solution(8.3), solution("a"), solution(-1), solution(None). Also solution(3.0) because isinstance(3.0, int) is False, even though the value is integral.

Common situations: CLI arguments passed as strings (argparse without type=int); JSON config with 10.0; computed digit counts that end up as floats (e.g. math.log results).

Related errors


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