TheAlgorithms/Python · error · ValueError

param `position` must be non-negative

Error message

param `position` must be non-negative

What it means

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.

Source

Thrown at maths/special_numbers/triangular_numbers.py:35

    Returns:
        int: The triangular number at the specified position.

    Raises:
        ValueError: If `position` is negative.

    Examples:
    >>> triangular_number(1)
    1
    >>> triangular_number(3)
    6
    >>> triangular_number(-1)
    Traceback (most recent call last):
        ...
    ValueError: param `position` must be non-negative
    """
    if position < 0:
        raise ValueError("param `position` must be non-negative")

    return position * (position + 1) // 2


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp or reject negative positions before calling: max(0, n) if a floor is acceptable
  2. Fix the upstream computation so the position cannot go negative (guard len(items) == 0 before len(items) - 1)
  3. Validate interactive/config input for position >= 0

Example fix

// before
t = triangular_number(len(items) - 1)  # ValueError when items is empty

// after
t = triangular_number(max(0, len(items) - 1))
Defensive patterns

Strategy: validation

Validate before calling

if position < 0:
    raise ValueError('position must be >= 0')
t = triangular_number(position)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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