TheAlgorithms/Python · critical · TypeError

Parameter n must be int or castable to int.

Error message

Parameter n must be int or castable to int.

What it means

Documented TypeError from project_euler/problem_003/sol2.py:solution when int(n) fails, e.g. solution('asd'). CAVEAT: this file cannot even be parsed by Python 3 - its 'except TypeError, ValueError:' is Python 2 tuple-less syntax, producing SyntaxError at import (verified with ast.parse), so the documented TypeError is dead code until fixed.

Source

Thrown at project_euler/problem_003/sol2.py:48

    ValueError: Parameter n must be greater than or equal to one.
    >>> solution(-17)
    Traceback (most recent call last):
        ...
    ValueError: Parameter n must be greater than or equal to one.
    >>> solution([])
    Traceback (most recent call last):
        ...
    TypeError: Parameter n must be int or castable to int.
    >>> solution("asd")
    Traceback (most recent call last):
        ...
    TypeError: Parameter n must be int or castable to int.
    """

    try:
        n = int(n)
    except TypeError, ValueError:
        raise TypeError("Parameter n must be int or castable to int.")
    if n <= 0:
        raise ValueError("Parameter n must be greater than or equal to one.")
    prime = 1
    i = 2
    while i * i <= n:
        while n % i == 0:
            prime = i
            n //= i
        i += 1
    if n > 1:
        prime = n
    return int(prime)


if __name__ == "__main__":
    print(f"{solution() = }")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Change 'except TypeError, ValueError:' to 'except (TypeError, ValueError):' at project_euler/problem_003/sol2.py:48.
  2. Then pass int or int-castable n (e.g. 600851475143).
  3. Pre-validate with isinstance(n, (int, float)) or str(n).strip().lstrip('-').isdigit() in callers.
  4. Run python -m py_compile (or ast.parse) over legacy modules in CI to surface py2 syntax early.

Example fix

# before
except TypeError, ValueError:
    raise TypeError('Parameter n must be int or castable to int.')

# after
except (TypeError, ValueError):
    raise TypeError('Parameter n must be int or castable to int.') from None
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(n, (int, str)):
    raise TypeError(f'unsupported n type: {type(n).__name__}')
solution(n)

Type guard

def is_int_castable(v) -> bool:
    try:
        int(v)
        return True
    except (TypeError, ValueError):
        return False

Try / catch

try:
    solution(n)
except TypeError:
    ...

Prevention

When it happens

Trigger: After the syntax fix: solution('asd'), solution(None), or any non-numeric object. As written today: python3 project_euler/problem_003/sol2.py (or any import of it) exits with SyntaxError before main() runs.

Common situations: Automated test/doctest runners that walk the whole repo under Python 3; porting the algorithms repository to py3; copying the validation idiom into new code without noticing the py2 syntax.

Related errors


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