{"record":{"id":"71a9918074c90ab5","repo":"TheAlgorithms/Python","slug":"param-position-must-be-non-negative","errorCode":null,"errorMessage":"param `position` must be non-negative","messagePattern":"param `position` must be non-negative","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/special_numbers/triangular_numbers.py","lineNumber":35,"sourceCode":"\n    Returns:\n        int: The triangular number at the specified position.\n\n    Raises:\n        ValueError: If `position` is negative.\n\n    Examples:\n    >>> triangular_number(1)\n    1\n    >>> triangular_number(3)\n    6\n    >>> triangular_number(-1)\n    Traceback (most recent call last):\n        ...\n    ValueError: param `position` must be non-negative\n    \"\"\"\n    if position < 0:\n        raise ValueError(\"param `position` must be non-negative\")\n\n    return position * (position + 1) // 2\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":17,"sourceCodeEnd":44,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/special_numbers/triangular_numbers.py#L17-L44","documentation":"Raised by triangular_number(position) in maths/special_numbers/triangular_numbers.py when position is negative. The n-th triangular number is position*(position+1)//2, well-defined for position >= 0 (triangular_number(0) == 0), so only strictly negative indices are rejected.","triggerScenarios":"Calling triangular_number(-1) or any negative argument. There is no type check — a float like 2.0 will not raise here but will return a float via the // expression's behavior on floats.","commonSituations":"Passing a computed count (e.g. len(items) - 1) that goes negative on empty input; off-by-one in loops that index from -1 by mistake.","solutions":["Clamp or reject negative positions before calling: max(0, n) if a floor is acceptable","Fix the upstream computation so the position cannot go negative (guard len(items) == 0 before len(items) - 1)","Validate interactive/config input for position >= 0"],"exampleFix":"// before\nt = triangular_number(len(items) - 1)  # ValueError when items is empty\n\n// after\nt = triangular_number(max(0, len(items) - 1))","handlingStrategy":"validation","validationCode":"if position < 0:\n    raise ValueError('position must be >= 0')\nt = triangular_number(position)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["position 0 is valid and returns 0 — only negatives raise","Guard computed positions like len(items) - 1 against empty inputs","There is no type check here: floats quietly return floats"],"tags":["math","valueerror","input-validation","triangular-numbers"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}