TheAlgorithms/Python · error · ValueError

The input value of [n={number}] has to be > 0

Error message

The input value of [n={number}] has to be > 0

What it means

Raised by sylvester(number) in maths/sylvester_sequence.py when number is a builtin int less than 1. The function computes the n-th Sylvester sequence term recursively (sylvester(1) == 2, then a(n) = a(n-1)^2 - a(n-1) + 1), so 0 and negative indices are rejected. The type check above it uses a bare assert, so non-integers raise AssertionError instead — another quirk of this module.

Source

Thrown at maths/sylvester_sequence.py:35

    113423713055421844361000443

    >>> sylvester(-1)
    Traceback (most recent call last):
        ...
    ValueError: The input value of [n=-1] has to be > 0

    >>> sylvester(8.0)
    Traceback (most recent call last):
        ...
    AssertionError: The input value of [n=8.0] is not an integer
    """
    assert isinstance(number, int), f"The input value of [n={number}] is not an integer"

    if number == 1:
        return 2
    elif number < 1:
        msg = f"The input value of [n={number}] has to be > 0"
        raise ValueError(msg)
    else:
        num = sylvester(number - 1)
        lower = num - 1
        upper = num
        return lower * upper + 1


if __name__ == "__main__":
    print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use indices >= 1: shift 0-based indices with sylvester(i + 1)
  2. Do not rely on the assert for validation — it disappears under `python -O`; validate types yourself
  3. Cap n for performance: terms explode in size (term 8 is already ~2^32 digits-scale growth per step)

Example fix

// before
v = sylvester(0)  # ValueError

// after
v = sylvester(1)  # 2
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(n, int) or isinstance(n, bool):
    raise TypeError('sylvester index must be an int')  # own check: assert vanishes under -O
if n < 1:
    raise ValueError('sylvester index must be >= 1')
v = sylvester(n)

Try / catch

try:
    v = sylvester(n)
except (ValueError, AssertionError) as e:
    raise ValueError(f'bad sylvester index {n!r}: {e}') from e

Prevention

When it happens

Trigger: Calling sylvester(0) or sylvester(-3). Note sylvester(8.0) raises AssertionError (not this ValueError) because the assert fires first; also note values grow doubly-exponentially, so large n is slow and huge.

Common situations: 0-based indexing into this 1-based sequence; running with python -O strips the assert, letting 8.0 slip through to a TypeError elsewhere — a subtle behavior change under optimized mode.

Related errors


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