TheAlgorithms/Python · error · TypeError

Both arguments MUST be integers!

Error message

Both arguments MUST be integers!

What it means

Raised by bitwise_addition_recursive when either argument is not an int. The algorithm computes the sum purely with ^, &, and << operators, so it requires true integers; floats and strings are rejected before any bit operation runs. Note that bool passes this check because bool subclasses int.

Source

Thrown at bit_manipulation/bitwise_addition_recursive.py:38

    Traceback (most recent call last):
        ...
    TypeError: Both arguments MUST be integers!
    >>> 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. Convert operands to int at the call site: bitwise_addition_recursive(int(a), int(b)).
  2. For ordinary addition just use a + b; keep this function for learning/benchmark scenarios where operands are already ints.
  3. If strictness beyond bool is needed, add `isinstance(x, bool)` exclusion before calling.

Example fix

# before
bitwise_addition_recursive(2.0, 3)  # TypeError

# after
bitwise_addition_recursive(int(2.0), 3)  # 5
Defensive patterns

Strategy: type-guard

Validate before calling

if not all(isinstance(x, int) and not isinstance(x, bool) for x in (number, other_number)):
    raise TypeError("bitwise addition needs true ints")

Type guard

def are_ints(*values: object) -> bool:
    return all(isinstance(v, int) for v in values)

Try / catch

try:
    total = bitwise_addition_recursive(a, b)
except TypeError:
    total = int(a) + int(b)

Prevention

When it happens

Trigger: Calling bitwise_addition_recursive(1.5, 2) or ('1', 2). Values that are ints pass through; True/False are accepted since isinstance(True, int) is True.

Common situations: Feeding parsed numeric strings or float results from math modules into a bitwise adder; mixing types from JSON/dynamic data without coercion.

Related errors


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