TheAlgorithms/Python · error · ValueError

Input must be a positive integer

Error message

Input must be a positive integer

What it means

Raised by liouville_lambda in maths/liouville_lambda.py when number is an int but less than 1. The Liouville function is defined only for positive integers (lambda(1) = 1, computed as the empty factorization); 0 and negatives have no prime factorization, so the guard rejects them with ValueError after the type check and before prime_factors is called.

Source

Thrown at maths/liouville_lambda.py:39

    -1
    >>> liouville_lambda(0)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a positive integer
    >>> liouville_lambda(-1)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a positive integer
    >>> liouville_lambda(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 -1 if len(prime_factors(number)) % 2 else 1


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Enumerate candidates from 1: range(1, n + 1).
  2. Validate bounds on user/computed input before the call.
  3. Skip non-positive entries when mapping over mixed-sign data.

Example fix

// before
values = [liouville_lambda(i) for i in range(len(data))]  # i=0 raises

// after
values = [liouville_lambda(i) for i in range(1, len(data) + 1)]
Defensive patterns

Strategy: validation

Validate before calling

if number < 1:
    raise ValueError(f"liouville_lambda needs number >= 1, got {number}")
lam = liouville_lambda(number)

Type guard

def is_positive_int(v) -> bool:
    return isinstance(v, int) and not isinstance(v, bool) and v >= 1

Try / catch

try:
    lam = liouville_lambda(i)
except ValueError:
    lam = None  # or skip index

Prevention

When it happens

Trigger: Calling liouville_lambda(0) or liouville_lambda(-1). Any int < 1 hits the raise; 1 is valid and returns 1 (len([]) % 2 == 0 -> 1).

Common situations: Enumerating from 0 in benchmark loops; signed differences or offsets producing non-positive values; reusing validation from a function whose domain starts at 0.

Related errors


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