TheAlgorithms/Python · error · ValueError
Length must be a positive integer.
Error message
Length must be a positive integer.
What it means
Raised by hexagonal_numbers() in maths/series/hexagonal_numbers.py when length is not an int or is <= 0. The function generates the first `length` hexagonal numbers via a list comprehension over range(length), so a negative, zero, or non-integer length is meaningless. Note the check order: `length <= 0 or not isinstance(length, int)` — a float like 5.0 is also rejected even though it equals a valid int.
Source
Thrown at maths/series/hexagonal_numbers.py:36
def hexagonal_numbers(length: int) -> list[int]:
"""
:param len: max number of elements
:type len: int
:return: Hexagonal numbers as a list
Tests:
>>> hexagonal_numbers(10)
[0, 1, 6, 15, 28, 45, 66, 91, 120, 153]
>>> hexagonal_numbers(5)
[0, 1, 6, 15, 28]
>>> hexagonal_numbers(0)
Traceback (most recent call last):
...
ValueError: Length must be a positive integer.
"""
if length <= 0 or not isinstance(length, int):
raise ValueError("Length must be a positive integer.")
return [n * (2 * n - 1) for n in range(length)]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=10))
View on GitHub (pinned to f5988cc097)
Solutions
- Coerce to int when the value is whole: hexagonal_numbers(int(n))
- Clamp or validate the computed length: length = max(1, int(length))
- Reject non-integer input at the UI/API boundary with a clear message
Example fix
# before hexagonal_numbers(n / 2) # float -> ValueError # after hexagonal_numbers(int(n / 2)) # or n // 2
Defensive patterns
Strategy: validation
Validate before calling
length = int(length) if isinstance(length, float) and length.is_integer() else length
if isinstance(length, int) and length > 0:
print(hexagonal_numbers(length)) Type guard
def is_positive_int(value: object) -> bool:
return isinstance(value, int) and not isinstance(value, bool) and value > 0 Prevention
- Use // instead of / for computed counts
- Parse CLI/JSON counts with int()
- Clamp computed lengths: max(1, int(n))
When it happens
Trigger: Calling hexagonal_numbers(0), hexagonal_numbers(-3), or hexagonal_numbers(5.0). Booleans pass (isinstance(True, int) is True) but length=False raises because False <= 0.
Common situations: User-supplied count parsed from a string without int() conversion; a computed length that went negative after subtraction; division results (e.g. n/2 in Python 3 yields float) passed directly.
Related errors
- Input list must be a non empty list
- Input list must be a non empty list
- {num}: Invalid input, please enter a positive integer.
- max_set_length must be non-negative
- Number {n} must instead be a positive integer
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/aced6bc80503458e.
Report an issue: GitHub.