TheAlgorithms/Python · error · ValueError

input must be a negative integer

Error message

input must be a negative integer

What it means

Raised by twos_complement when number is positive. The function computes the two's-complement bit pattern of a negative integer; a positive input has no meaning for this operation, so it is rejected. Zero is accepted and returns '0b0' via the else branch.

Source

Thrown at bit_manipulation/binary_twos_complement.py:25

    Return the two's complement representation of 'number'.

    >>> twos_complement(0)
    '0b0'
    >>> twos_complement(-1)
    '0b11'
    >>> twos_complement(-5)
    '0b1011'
    >>> twos_complement(-17)
    '0b101111'
    >>> twos_complement(-207)
    '0b100110001'
    >>> twos_complement(1)
    Traceback (most recent call last):
        ...
    ValueError: input must be a negative integer
    """
    if number > 0:
        raise ValueError("input must be a negative integer")
    binary_number_length = len(bin(number)[3:])
    twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]
    twos_complement_number = (
        (
            "1"
            + "0" * (binary_number_length - len(twos_complement_number))
            + twos_complement_number
        )
        if number < 0
        else "0"
    )
    return "0b" + twos_complement_number


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Ensure the value is negative: call twos_complement(-abs(number)) when you want the two's complement of a magnitude.
  2. Branch at the call site: handle number >= 0 separately (e.g., plain bin(number)) and only route negatives to this function.
  3. If you need arbitrary-width two's complement, format manually: format(number & (1 << width) - 1, f'0{width}b').

Example fix

# before
twos_complement(5)  # ValueError

# after
if number < 0:
    result = twos_complement(number)
else:
    result = '0b' + format(number, 'b')
Defensive patterns

Strategy: validation

Validate before calling

if number > 0:
    raise ValueError("twos_complement expects a negative integer")

Type guard

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

Prevention

When it happens

Trigger: Calling twos_complement(1) or any positive integer. twos_complement(0) does not raise; only number > 0 triggers the error.

Common situations: Normalizing signs before encoding signed values (e.g., building fixed-width representations) and forgetting the positive branch; feeding magnitudes where signed negatives were expected.

Related errors


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