TheAlgorithms/Python · error · ValueError

the value of both inputs must be positive

Error message

the value of both inputs must be positive

What it means

Raised by binary_xor when either input is negative. The function XORs two numbers by comparing their zero-padded binary strings, which assumes non-negative operands. Zero is accepted despite the 'positive' wording because the guard is `a < 0 or b < 0`.

Source

Thrown at bit_manipulation/binary_xor_operator.py:36

    >>> binary_xor(0, 255)
    '0b11111111'
    >>> binary_xor(256, 256)
    '0b000000000'
    >>> binary_xor(0, -1)
    Traceback (most recent call last):
        ...
    ValueError: the value of both inputs must be positive
    >>> binary_xor(0, 1.1)
    Traceback (most recent call last):
        ...
    TypeError: 'float' object cannot be interpreted as an integer
    >>> binary_xor("0", "1")
    Traceback (most recent call last):
        ...
    TypeError: '<' not supported between instances of 'str' and 'int'
    """
    if a < 0 or b < 0:
        raise ValueError("the value of both inputs must be positive")

    a_binary = str(bin(a))[2:]  # remove the leading "0b"
    b_binary = str(bin(b))[2:]  # remove the leading "0b"

    max_len = max(len(a_binary), len(b_binary))

    return "0b" + "".join(
        str(int(char_a != char_b))
        for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
    )


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use Python's native a ^ b if you need XOR of possibly-negative ints; this helper is string-based and unsigned-only.
  2. Pass abs() of the operands when only magnitudes matter.
  3. Validate a >= 0 and b >= 0 at the call site before invoking binary_xor.

Example fix

# before
binary_xor(delta, mask)  # ValueError when delta < 0

# after
binary_xor(abs(delta), abs(mask))
Defensive patterns

Strategy: validation

Validate before calling

if a < 0 or b < 0:
    raise ValueError(f"binary_xor requires non-negative ints, got {a}, {b}")

Prevention

When it happens

Trigger: Calling binary_xor(-1, 1) or any call where at least one argument is a negative int. Floats pass the guard and fail later in bin(); strings fail at the `<` comparison.

Common situations: XOR-based checksums or pairwise-cancellation logic fed with signed differences or deltas; passing values from subtraction without abs().

Related errors


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