TheAlgorithms/Python · error · ValueError
vol_cube() only accepts non-negative values
Error message
vol_cube() only accepts non-negative values
What it means
Raised by vol_cube(side_length) in maths/volume.py when side_length is negative. The cube volume is side_length**3, physically meaningless for negative lengths, so the guard rejects them; 0 is explicitly allowed (returns 0.0) and floats are accepted.
Source
Thrown at maths/volume.py:31
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
1.0
>>> vol_cube(3)
27.0
>>> vol_cube(0)
0.0
>>> vol_cube(1.6)
4.096000000000001
>>> vol_cube(-1)
Traceback (most recent call last):
...
ValueError: vol_cube() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("vol_cube() only accepts non-negative values")
return pow(side_length, 3)
def vol_spherical_cap(height: float, radius: float) -> float:
"""
Calculate the volume of the spherical cap.
>>> vol_spherical_cap(1, 2)
5.235987755982988
>>> vol_spherical_cap(1.6, 2.6)
16.621119532592402
>>> vol_spherical_cap(0, 0)
0.0
>>> vol_spherical_cap(-1, 2)
Traceback (most recent call last):
...
ValueError: vol_spherical_cap() only accepts non-negative values
>>> vol_spherical_cap(1, -2)View on GitHub (pinned to f5988cc097)
Solutions
- Validate measurement sign at ingestion: lengths must be >= 0
- If the value may be a magnitude error, take abs() only when that is physically justified — otherwise reject the input
- Pre-check with your own guard: if side < 0: reject before calling
Example fix
// before v = vol_cube(-1) # ValueError // after v = vol_cube(abs(-1)) if magnitude_only else vol_cube(1)
Defensive patterns
Strategy: validation
Validate before calling
if side_length < 0:
raise ValueError(f'invalid cube side {side_length}')
v = vol_cube(side_length) Prevention
- Validate measurement signs at ingestion
- Only abs() a negative length when the sign is known to be a data-entry slip
- Zero is legal and returns 0.0
When it happens
Trigger: Calling vol_cube(-1) with any negative value. There is no type check — strings will fail later with a TypeError from the comparison/pow, not with this message.
Common situations: Geometry inputs parsed from user data or measurements where a minus sign slipped in; symmetric-error propagation (e.g. delta = a - b) producing negative 'lengths'.
Related errors
- vol_spherical_cap() only accepts non-negative values
- surface_area_cube() only accepts non-negative values
- surface_area_cuboid() only accepts non-negative values
- surface_area_sphere() only accepts non-negative values
- surface_area_hemisphere() only accepts non-negative values
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/2a5cc4b82fd59ab5.
Report an issue: GitHub.