TheAlgorithms/Python · error · ValueError

number must not be negative

Error message

number must not be negative

What it means

Raised by is_power_of_two when number is negative. The classic check number & (number - 1) == 0 only identifies powers of two for non-negative integers, so negatives are rejected. There is no type guard: floats like 1.2 pass this check and fail later with a TypeError from the & operator.

Source

Thrown at bit_manipulation/is_power_of_two.py:50

    >>> is_power_of_two(8)
    True
    >>> is_power_of_two(17)
    False
    >>> is_power_of_two(-1)
    Traceback (most recent call last):
        ...
    ValueError: number must not be negative
    >>> is_power_of_two(1.2)
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for &: 'float' and 'float'

    # Test all powers of 2 from 0 to 10,000
    >>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
    True
    """
    if number < 0:
        raise ValueError("number must not be negative")
    return number & (number - 1) == 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate at the boundary: require value > 0 (and int) before calling if a true power of two is expected.
  2. Handle the 0 case explicitly if is_power_of_two(0) == True would be wrong for your logic.
  3. Use n > 0 and (n & (n - 1)) == 0 inline for a guard-free, well-defined check on any int.

Example fix

# before
is_power_of_two(size)  # ValueError when size < 0

# after
is_power_of_two(size) if size >= 0 else False
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(number, int) or number <= 0:
    is_pow2 = False
else:
    is_pow2 = is_power_of_two(number)

Type guard

def is_positive_int(n: object) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n > 0

Prevention

When it happens

Trigger: Calling is_power_of_two(-1), (-16), or any negative int. is_power_of_two(1.2) does NOT raise this — it raises TypeError from `&` between floats. Also note is_power_of_two(0) returns True (quirk of the same guard).

Common situations: Validating sizes, capacities, or alignment values that can be configured negative; passing signed deltas into a power-of-two check.

Related errors


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