TheAlgorithms/Python · error · ValueError

{num}: Invalid input, please enter a positive integer.

Error message

{num}: Invalid input, please enter a positive integer.

What it means

Raised by prime_sieve() in maths/sieve_of_eratosthenes.py when num <= 0. The sieve allocates [True] * (num + 1) and marks composites from 2 upward; zero and negative numbers have no primes below them, so the input is rejected up front. num=1 is valid and returns [] (empty prime list).

Source

Thrown at maths/sieve_of_eratosthenes.py:39

    Returns a list with all prime numbers up to n.

    >>> prime_sieve(50)
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    >>> prime_sieve(25)
    [2, 3, 5, 7, 11, 13, 17, 19, 23]
    >>> prime_sieve(10)
    [2, 3, 5, 7]
    >>> prime_sieve(9)
    [2, 3, 5, 7]
    >>> prime_sieve(2)
    [2]
    >>> prime_sieve(1)
    []
    """

    if num <= 0:
        msg = f"{num}: Invalid input, please enter a positive integer."
        raise ValueError(msg)

    sieve = [True] * (num + 1)
    prime = []
    start = 2
    end = int(math.sqrt(num))

    while start <= end:
        # If start is a prime
        if sieve[start] is True:
            prime.append(start)

            # Set multiples of start be False
            for i in range(start * start, num + 1, start):
                if sieve[i] is True:
                    sieve[i] = False

        start += 1

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp to the smallest meaningful bound: prime_sieve(max(2, num))
  2. Validate the bound at the source: if num < 1: raise/skip early in your own code
  3. Treat num <= 1 as 'no primes' and return [] yourself before calling

Example fix

# before
primes = prime_sieve(upper - lower)  # can be <= 0

# after
span = upper - lower
primes = prime_sieve(span) if span >= 1 else []
Defensive patterns

Strategy: validation

Validate before calling

primes = prime_sieve(num) if num >= 1 else []

Type guard

def is_positive_int(value: object) -> bool:
    return isinstance(value, int) and value > 0

Prevention

When it happens

Trigger: Calling prime_sieve(0) or prime_sieve(-5). Note the message interpolates the offending value, e.g. '-5: Invalid input, please enter a positive integer.'. Non-integer input is not checked here and may fail elsewhere (e.g. float triggers a TypeError at list multiplication).

Common situations: Boundary code where the upper limit comes from a subtraction (limit - offset) that can go negative; off-by-one loops passing 0; parsing optional CLI args whose default is 0.

Related errors


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