TheAlgorithms/Python · error · ValueError

Input must be a non-negative integer

Error message

Input must be a non-negative integer

What it means

Raised by find_previous_power_of_two when the input is not an int or is negative. The function doubles a power counter until it exceeds the number, logic that requires a non-negative integer; both bad types and negative values raise the same ValueError.

Source

Thrown at bit_manipulation/find_previous_power_of_two.py:18

def find_previous_power_of_two(number: int) -> int:
    """
    Find the largest power of two that is less than or equal to a given integer.
    https://stackoverflow.com/questions/1322510

    >>> [find_previous_power_of_two(i) for i in range(18)]
    [0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
    >>> find_previous_power_of_two(-5)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    >>> find_previous_power_of_two(10.5)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    """
    if not isinstance(number, int) or number < 0:
        raise ValueError("Input must be a non-negative integer")
    if number == 0:
        return 0
    power = 1
    while power <= number:
        power <<= 1  # Equivalent to multiplying by 2
    return power >> 1 if number > 1 else 1


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Round down whole floats first: find_previous_power_of_two(int(size)) or math.floor for floats.
  2. Validate configuration values (size >= 0, integer) at load time before use.
  3. For bit_length-capable inputs, use 1 << (n.bit_length() - 1) as a direct equivalent for n >= 2.

Example fix

# before
find_previous_power_of_two(10.5)  # ValueError

# after
find_previous_power_of_two(int(10.5))  # 8
Defensive patterns

Strategy: validation

Validate before calling

import math
size = int(math.floor(size))
if size < 0:
    raise ValueError("size must be non-negative")

Type guard

def is_non_negative_int(n: object) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n >= 0

Prevention

When it happens

Trigger: Calling find_previous_power_of_two(-5) or find_previous_power_of_two(10.5). 0 is valid and returns 0.

Common situations: Sizing buffers/caches from computed capacities (e.g., ratio or average) that come out as floats; passing user-configured sizes without validation.

Related errors


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