TheAlgorithms/Python · error · ValueError

Input must be a positive integer

Error message

Input must be a positive integer

What it means

Raised by hexagonal(number) when the argument is a builtin int but is less than 1. The hexagonal sequence 1, 6, 15, 28, ... is indexed from 1, so there is no 0th or negative hexagonal number and the guard rejects them after the isinstance check passes.

Source

Thrown at maths/special_numbers/hexagonal_number.py:42

    946
    >>> hexagonal(0)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a positive integer
    >>> hexagonal(-1)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a positive integer
    >>> hexagonal(11.0)
    Traceback (most recent call last):
        ...
    TypeError: Input value of [number=11.0] must be an integer
    """
    if not isinstance(number, int):
        msg = f"Input value of [number={number}] must be an integer"
        raise TypeError(msg)
    if number < 1:
        raise ValueError("Input must be a positive integer")
    return number * (2 * number - 1)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Start loops at 1: `for n in range(1, count + 1)`
  2. If you have a 0-based index, add 1 before calling: hexagonal(idx + 1)
  3. Validate that user-supplied positions are >= 1 before invoking

Example fix

// before
h = hexagonal(0)  # ValueError

// after
h = hexagonal(0 + 1)  # first hexagonal number
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or n < 1:
    raise ValueError('hexagonal index must be a positive int')
h = hexagonal(n)

Prevention

When it happens

Trigger: Calling hexagonal(0), hexagonal(-1), or any negative/zero integer. Non-integers raise the TypeError instead because the type check runs first.

Common situations: Off-by-one loop bounds (range(0, n) instead of range(1, n+1)); passing a 0-based index from another sequence API into this 1-based API without shifting.

Related errors


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