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 get_1s_count (Brian Kernighan popcount) when the input is not an int or is negative. The loop `number &= number - 1` relies on integer semantics and terminates only for non-negative values, so both wrong types and negative values are rejected with a single ValueError.

Source

Thrown at bit_manipulation/count_1s_brian_kernighan_method.py:31

    >>> get_1s_count(0)
    0
    >>> get_1s_count(256)
    1
    >>> get_1s_count(-1)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    >>> get_1s_count(0.8)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    >>> get_1s_count("25")
    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")

    count = 0
    while number:
        # This way we arrive at next set bit (next 1) instead of looping
        # through each bit and checking for 1s hence the
        # loop won't run 32 times it will only run the number of `1` times
        number &= number - 1
        count += 1
    return count


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert first: get_1s_count(int(value)) when value is a numeric string or whole float.
  2. For bitmasks built from ranges, ensure you pass range bounds or indices that are already ints.
  3. Prefer Python 3.10+ int.bit_count() which is faster and equally strict.

Example fix

# before
get_1s_count('25')  # ValueError

# after
get_1s_count(int('25'))  # 3
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(number, int) or isinstance(number, bool) or number < 0:
    raise ValueError("popcount needs a non-negative int")

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 get_1s_count(0.8), get_1s_count('25'), or get_1s_count(-3). Any non-int type or negative integer triggers it.

Common situations: Counting set bits in data that arrived as strings or floats (CSV parsing, JSON numbers, len() results used as bitmasks); assuming the function does its own coercion.

Related errors


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