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_002/sol4.py:solution when n cannot be converted with int(n) (e.g. 'asd', None). CRITICAL CAVEAT: the guard is written as 'except TypeError, ValueError:', which is Python 2 syntax - this file raises SyntaxError at import under Python 3, so this TypeError is currently unreachable until the except clause is fixed to 'except (TypeError, ValueError):'.

Source

Thrown at project_euler/problem_002/sol4.py:60

    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.")
    getcontext().prec = 100
    phi = (Decimal(5) ** Decimal("0.5") + 1) / Decimal(2)

    index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2
    num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2)
    total = num // 2
    return int(total)


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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Fix the syntax first: change 'except TypeError, ValueError:' to 'except (TypeError, ValueError):' in project_euler/problem_002/sol4.py:60.
  2. After the fix, pass an int or an int-castable value such as '100' or 100.0.
  3. Pre-validate with isinstance(n, int) or str(n).isdigit() before calling.
  4. Add the module to a doctest/CI run so the SyntaxError cannot regress.

Example fix

# before (Python 2 syntax - SyntaxError under Python 3)
try:
    n = int(n)
except TypeError, ValueError:
    raise TypeError('Parameter n must be int or castable to int.')

# after
try:
    n = int(n)
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, float)) and not str(n).lstrip('-').isdigit():
    raise TypeError(f'n must be int-castable, got {n!r}')
solution(n)

Type guard

def is_int_castable(v) -> bool:
    if isinstance(v, bool):
        return False
    if isinstance(v, (int, float)):
        return float(v).is_integer() or isinstance(v, int)
    try:
        int(v)
        return True
    except (TypeError, ValueError):
        return False

Try / catch

try:
    solution(n)
except TypeError as e:
    if 'castable' in str(e):
        ...

Prevention

When it happens

Trigger: After fixing the syntax: calling solution('asd'), solution(None), or any object where int(n) raises. As written today: merely importing or running the module under Python 3 raises SyntaxError('multiple exception types must be parenthesized') before any call.

Common situations: Running the repository's Python-2-era solution files under Python 3 (the repo predates the py2->py3 migration of these guards); doctest suites that fail with SyntaxError instead of the documented TypeError; copy-pasting this validation idiom into new code.

Related errors


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