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
- 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
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
- 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
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
- surface_area_cube() only accepts non-negative values
- surface_area_cuboid() only accepts non-negative values
- surface_area_sphere() only accepts non-negative values
- surface_area_hemisphere() only accepts non-negative values
- surface_area_cone() only accepts non-negative values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/71a9918074c90ab5.
Report an issue: GitHub.