TheAlgorithms/Python · error · ValueError

k integer must be greater or equal to zero.

Error message

k integer must be greater or equal to zero.

What it means

Raised by the fibonacci helper in searches/fibonacci_search.py when k is a negative integer. The helper defines Fibonacci numbers for indices 0 and 1 and recurses downward, so negative indices have no base case and would recurse forever (until RecursionError); the guard rejects them up front with ValueError. It fires only after the isinstance(k, int) check, so the value is a genuine negative int.

Source

Thrown at searches/fibonacci_search.py:49

    >>> fibonacci(0)
    0
    >>> fibonacci(2)
    1
    >>> fibonacci(5)
    5
    >>> fibonacci(15)
    610
    >>> fibonacci('a')
    Traceback (most recent call last):
    TypeError: k must be an integer.
    >>> fibonacci(-5)
    Traceback (most recent call last):
    ValueError: k integer must be greater or equal to zero.
    """
    if not isinstance(k, int):
        raise TypeError("k must be an integer.")
    if k < 0:
        raise ValueError("k integer must be greater or equal to zero.")
    if k == 0:
        return 0
    elif k == 1:
        return 1
    else:
        return fibonacci(k - 1) + fibonacci(k - 2)


def fibonacci_search(arr: list, val: int) -> int:
    """A pure Python implementation of a fibonacci search algorithm.

    Parameters
    ----------
    arr
        List of sorted elements.
    val
        Element to search in list.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Only call with k >= 0; index 0 returns 0 and index 1 returns 1.
  2. Clamp or reject at your boundary: if k < 0: raise ValueError(...).
  3. If negative Fibonacci (Fibonacci extension) is actually wanted, use an explicit closed-form/Binet implementation, not this helper.

Example fix

# before
fibonacci(n - 2)  # n = 1 -> fibonacci(-1) -> ValueError

# after
if n - 2 < 0:
    return n  # base case handled by caller
fibonacci(n - 2)
Defensive patterns

Strategy: validation

Validate before calling

if k < 0:
    raise ValueError(f'k must be >= 0, got {k}')
fibonacci(k)

Try / catch

try:
    fib_k = fibonacci(k)
except ValueError:
    fib_k = fibonacci(abs(k))  # only if negative indexing is semantically wrong input

Prevention

When it happens

Trigger: fibonacci(-5); fibonacci(-1); passing a loop variable that underflows below zero, e.g. a while k >= 0 loop rewritten incorrectly.

Common situations: Index arithmetic that goes negative during searches; validating untrusted numeric input without a lower bound; porting code from languages where negative indexing is meaningful.

Related errors


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