TheAlgorithms/Python · error · ValueError

number must be a positive integer

Error message

number must be a positive integer

What it means

Raised by int_to_base() when number is negative. The algorithm repeatedly divmods a non-negative integer to extract digits and has no path for a minus sign, so negative inputs are rejected up front. Note the message says 'positive' but 0 is actually accepted and returns '0'.

Source

Thrown at maths/special_numbers/harshad_numbers.py:44

    ValueError: 'base' must be between 2 and 36 inclusive
    >>> int_to_base(98, 37)
    Traceback (most recent call last):
        ...
    ValueError: 'base' must be between 2 and 36 inclusive
    >>> int_to_base(-99, 16)
    Traceback (most recent call last):
        ...
    ValueError: number must be a positive integer
    """

    if base < 2 or base > 36:
        raise ValueError("'base' must be between 2 and 36 inclusive")

    digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""

    if number < 0:
        raise ValueError("number must be a positive integer")

    while number > 0:
        number, remainder = divmod(number, base)
        result = digits[remainder] + result

    if result == "":
        result = "0"

    return result


def sum_of_digits(num: int, base: int) -> str:
    """
    Calculate the sum of digit values in a positive integer
    converted to the given 'base'.
    Where 'base' ranges from 2 to 36.

    Examples:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Take abs(number) before converting if you only need the magnitude's digits
  2. Reject or handle negative inputs at your own call site before passing them down
  3. If a signed representation is required, prefix '-' yourself after converting the absolute value

Example fix

// before
s = int_to_base(-99, 16)  # ValueError

// after
s = ('-' if n < 0 else '') + int_to_base(abs(-99), 16)
Defensive patterns

Strategy: validation

Validate before calling

def to_base_signed(n: int, base: int) -> str:
    sign = '-' if n < 0 else ''
    return sign + int_to_base(abs(n), base)

Try / catch

try:
    s = int_to_base(n, base)
except ValueError as e:
    if 'positive' in str(e):
        s = '-' + int_to_base(-n, base)
    else:
        raise

Prevention

When it happens

Trigger: Calling int_to_base(number, base) with any number < 0, e.g. int_to_base(-99, 16). Base is validated first, so a bad base on a negative number raises the base error instead.

Common situations: Feeding unchecked signed arithmetic results or parsed negative user input into the converter; forgetting that this API, unlike Python's built-in hex()/oct(), has no negative-number support.

Related errors


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