TheAlgorithms/Python · error · ValueError
Invalid input: num must be >= 0 and sides must be >= 3.
Error message
Invalid input: num must be >= 0 and sides must be >= 3.
What it means
Raised by polygonal_num(sides, num) in maths/special_numbers/polygonal_numbers.py when num < 0 or sides < 3. The closed-form formula ((sides-2)*num^2 - (sides-4)*num) // 2 needs a non-negative index and at least 3 sides (a polygon cannot have fewer), hence the combined guard with a single message.
Source
Thrown at maths/special_numbers/polygonal_numbers.py:24
>>> polygonal_num(0, 3)
0
>>> polygonal_num(3, 3)
6
>>> polygonal_num(5, 4)
25
>>> polygonal_num(2, 5)
5
>>> polygonal_num(-1, 0)
Traceback (most recent call last):
...
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
>>> polygonal_num(0, 2)
Traceback (most recent call last):
...
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
"""
if num < 0 or sides < 3:
raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.")
return ((sides - 2) * num**2 - (sides - 4) * num) // 2
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Double-check argument order: index first, sides second
- Ensure sides >= 3 (triangles are the minimum) and num >= 0 in your loops and inputs
- Use keyword arguments if unsure: polygonal_num(num=2, sides=5)
Example fix
// before val = polygonal_num(0, 2) # ValueError: sides < 3 // after val = polygonal_num(0, 3) # first triangular number
Defensive patterns
Strategy: validation
Validate before calling
def safe_polygonal(num: int, sides: int) -> int:
if num < 0:
raise ValueError('num (index) must be >= 0')
if sides < 3:
raise ValueError('sides must be >= 3 (triangle is the minimum)')
return polygonal_num(num, sides) Prevention
- Argument order is (num, sides): index first
- sides starts at 3, not 2
- Use keyword args when unsure: polygonal_num(num=2, sides=5)
When it happens
Trigger: Calling polygonal_num(-1, 0) (negative num) or polygonal_num(0, 2) (sides < 3). Note the parameter order in the doctests: the first argument is the index (num), the second is sides — polygonal_num(2, 5) returns the 2nd pentagonal number, 5.
Common situations: Swapping the two positional arguments so a valid sides value lands in num's slot; looping sides from 2 (forgetting that digons are excluded); passing a negative index for 'previous element' semantics this API does not have.
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/f3af4716706687a3.
Report an issue: GitHub.