TheAlgorithms/Python · error · ValueError

Both arguments MUST be non-negative!

Error message

Both arguments MUST be non-negative!

What it means

Raised by bitwise_addition_recursive when either argument is negative. The recursive carry loop (sum = a^b, carry = (a&b) << 1) only converges for non-negative integers; with negatives the carry never terminates correctly, so they are rejected up front.

Source

Thrown at bit_manipulation/bitwise_addition_recursive.py:41

    >>> bitwise_addition_recursive('4.5', 9)
    Traceback (most recent call last):
        ...
    TypeError: Both arguments MUST be integers!
    >>> bitwise_addition_recursive(-1, 9)
    Traceback (most recent call last):
        ...
    ValueError: Both arguments MUST be non-negative!
    >>> bitwise_addition_recursive(1, -9)
    Traceback (most recent call last):
        ...
    ValueError: Both arguments MUST be non-negative!
    """

    if not isinstance(number, int) or not isinstance(other_number, int):
        raise TypeError("Both arguments MUST be integers!")

    if number < 0 or other_number < 0:
        raise ValueError("Both arguments MUST be non-negative!")

    bitwise_sum = number ^ other_number
    carry = number & other_number

    if carry == 0:
        return bitwise_sum

    return bitwise_addition_recursive(bitwise_sum, carry << 1)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use the built-in + operator for signed addition; this function is inherently unsigned.
  2. Handle signs explicitly: compute on abs() values and reapply the sign, mirroring manual signed addition.
  3. Validate operands are >= 0 before the call and route negatives elsewhere.

Example fix

# before
bitwise_addition_recursive(-1, 9)  # ValueError

# after
if a < 0 or b < 0:
    result = a + b
else:
    result = bitwise_addition_recursive(a, b)
Defensive patterns

Strategy: validation

Validate before calling

if number < 0 or other_number < 0:
    raise ValueError("operands must be non-negative for bitwise addition")

Try / catch

try:
    total = bitwise_addition_recursive(a, b)
except ValueError:
    total = a + b  # fall back to native addition for signed input

Prevention

When it happens

Trigger: Calling bitwise_addition_recursive(-1, 9) or (1, -9) — either argument negative triggers it.

Common situations: Using the XOR-carry trick as a novelty adder on signed arithmetic, deltas, or subtraction results where one side can be negative.

Related errors


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