TheAlgorithms/Python · error · ValueError

both inputs must be positive integers

Error message

both inputs must be positive integers

What it means

Raised by logical_left_shift when either number or shift_amount is negative. A logical left shift appends zero bits to the binary representation, which is only defined for non-negative operands, so negative inputs are rejected up front.

Source

Thrown at bit_manipulation/binary_shifts.py:29

    Return the shifted binary representation.

    >>> logical_left_shift(0, 1)
    '0b00'
    >>> logical_left_shift(1, 1)
    '0b10'
    >>> logical_left_shift(1, 5)
    '0b100000'
    >>> logical_left_shift(17, 2)
    '0b1000100'
    >>> logical_left_shift(1983, 4)
    '0b111101111110000'
    >>> logical_left_shift(1, -1)
    Traceback (most recent call last):
        ...
    ValueError: both inputs must be positive integers
    """
    if number < 0 or shift_amount < 0:
        raise ValueError("both inputs must be positive integers")

    binary_number = str(bin(number))
    binary_number += "0" * shift_amount
    return binary_number


def logical_right_shift(number: int, shift_amount: int) -> str:
    """
    Take in positive 2 integers.
    'number' is the integer to be logically right shifted 'shift_amount' times.
    i.e. (number >>> shift_amount)
    Return the shifted binary representation.

    >>> logical_right_shift(0, 1)
    '0b0'
    >>> logical_right_shift(1, 1)
    '0b0'
    >>> logical_right_shift(1, 5)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard the computed shift amount: only call when shift_amount >= 0, else skip or use logical_right_shift.
  2. Use max(0, shift_amount) if shifting by a negative amount should be a no-op in your logic.
  3. For plain integer arithmetic, use number << shift_amount directly, which raises its own ValueError for negative shifts.

Example fix

# before
logical_left_shift(1, bits_a - bits_b)  # ValueError when bits_b > bits_a

# after
shift = max(0, bits_a - bits_b)
logical_left_shift(1, shift)
Defensive patterns

Strategy: validation

Validate before calling

shift = max(0, shift_amount)
if number < 0:
    raise ValueError("number must be non-negative")

Prevention

When it happens

Trigger: Calling logical_left_shift(1, -1), logical_left_shift(-4, 2), or any call where either argument is a negative int.

Common situations: Computing shift amounts dynamically (e.g., shift = bit_length(a) - bit_length(b)) where the expression can go negative for small inputs; passing user-supplied exponents without range checks.

Related errors


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