TheAlgorithms/Python · error · ValueError
number must be positive
Error message
number must be positive
What it means
Raised by power_of_4() when the argument passes the isinstance(number, int) check but is zero or negative. The function only defines 'power of 4' for positive integers (1, 4, 16, 64, ...), so any non-positive value is rejected before the bit-trick logic runs.
Source
Thrown at bit_manipulation/power_of_4.py:53
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
- Pass a positive integer: power_of_4(4) -> True.
- If 0/negative can occur, clamp or reject upstream: max(1, n) or an explicit if n <= 0 guard.
- For float support questions, note floats raise TypeError ('number must be an integer') instead — convert with int() first if that is intended.
Example fix
# before
power_of_4(0) # ValueError: number must be positive
# after
if n > 0:
power_of_4(n)
else:
raise ValueError(f"expected positive int, got {n}") Defensive patterns
Strategy: validation
Validate before calling
def is_valid_power_of_4_arg(n) -> bool:
return isinstance(n, int) and n > 0 Type guard
def is_positive_int(n: object) -> bool:
return isinstance(n, int) and not isinstance(n, bool) and n > 0 Try / catch
try:
power_of_4(n)
except ValueError as e:
if 'positive' in str(e):
handle_nonpositive(n)
else:
raise Prevention
- Validate n > 0 at the data source before calling bit-manipulation helpers.
- Remember floats raise TypeError here — convert deliberately with int().
When it happens
Trigger: Calling power_of_4(0), power_of_4(-4), or any int <= 0. Note booleans pass too since bool is a subclass of int, but power_of_4(False) == power_of_4(0) also triggers it.
Common situations: Passing a computed index/offset that can be 0, forwarding user input without range validation, or porting code from a language where 0 is acceptable.
Related errors
- The value of input must be non-negative
- Input value must be a 'int' type
- the value of both inputs must be positive
- both inputs must be positive integers
- input must be a negative integer
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/9aec39dcdf42c9c0.
Report an issue: GitHub.