TheAlgorithms/Python · error · TypeError

number must be an integer

Error message

number must be an integer

What it means

Raised by power_of_4 when the argument is not an int. The function first checks the type (this TypeError), then positivity (separate ValueError for number <= 0), then uses bit tricks — number & (number - 1) == 0 plus an odd bit-length — that only make sense for positive integers. Note bool passes the isinstance check.

Source

Thrown at bit_manipulation/power_of_4.py:51

    False
    >>> power_of_4(8)
    False
    >>> power_of_4(17)
    False
    >>> power_of_4(64)
    True
    >>> power_of_4(-1)
    Traceback (most recent call last):
        ...
    ValueError: number must be positive
    >>> power_of_4(1.2)
    Traceback (most recent call last):
        ...
    TypeError: number must be an integer

    """
    if not isinstance(number, int):
        raise TypeError("number must be an integer")
    if number <= 0:
        raise ValueError("number must be positive")
    if number & (number - 1) == 0:
        c = 0
        while number:
            c += 1
            number >>= 1
        return c % 2 == 1
    else:
        return False


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert at the call site: power_of_4(int(value)) for whole-number inputs.
  2. Validate dimension/size inputs as positive ints where they enter the program.
  3. Inline alternative without the helper: n > 0 and n & (n - 1) == 0 and n.bit_length() % 2 == 1.

Example fix

# before
power_of_4(1.2)  # TypeError

# after
power_of_4(int(1.2)) if float(1.2).is_integer() else False
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(number, int) or isinstance(number, bool):
    raise TypeError("number must be an integer")
if number <= 0:
    raise ValueError("number must be positive")

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 power_of_4(1.2), ('16',), or (None). power_of_4(-1) raises the sibling ValueError instead; power_of_4(0) also raises ValueError.

Common situations: Validating numeric config parsed from strings/JSON; passing float math results when checking alignment or power-of-four constraints (image dims, texture sizes, bucket counts).

Related errors


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