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_or when either input is negative. The function builds the OR of two numbers from their binary string representations, which assumes non-negative values. Despite the 'must be positive' wording, 0 is accepted because the guard is `a < 0 or b < 0`.

Source

Thrown at bit_manipulation/binary_or_operator.py:35

    >>> binary_or(0, 255)
    '0b11111111'
    >>> binary_or(0, 256)
    '0b100000000'
    >>> binary_or(0, -1)
    Traceback (most recent call last):
        ...
    ValueError: the value of both inputs must be positive
    >>> binary_or(0, 1.1)
    Traceback (most recent call last):
        ...
    TypeError: 'float' object cannot be interpreted as an integer
    >>> binary_or("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:]
    max_len = max(len(a_binary), len(b_binary))
    return "0b" + "".join(
        str(int("1" in (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. Pass abs(a) / abs(b) if the sign is irrelevant to your bit logic.
  2. Fix the caller to clamp or validate the value range before invoking binary_or.
  3. If negative numbers must be supported, use Python's native a | b and format with bin() instead of this helper.

Example fix

# before
binary_or(-3, 5)  # ValueError

# after
binary_or(abs(-3), 5)  # '0b111'
Defensive patterns

Strategy: validation

Validate before calling

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

Try / catch

try:
    result = binary_or(a, b)
except ValueError:
    result = binary_or(abs(a), abs(b))  # only if sign is truly irrelevant

Prevention

When it happens

Trigger: Calling binary_or(-1, 1), binary_or(3, -2), or any call where at least one argument is a negative int. Floats like (0, 1.1) pass this guard and fail later with TypeError from bin(); strings fail at the `<` comparison.

Common situations: Feeding signed integers from parsers, offsets, deltas, or subtraction results into a function that assumes unsigned bit patterns.

Related errors


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