TheAlgorithms/Python · error · ValueError
The mass of a body cannot be negative
Error message
The mass of a body cannot be negative
What it means
Raised by potential_energy(mass, height) in physics/potential_energy.py when mass < 0. Gravitational potential energy U = m*g*h requires a non-negative mass; mass 0 is allowed and returns 0.0. The mass check runs first, so a negative mass raises even if height is also invalid.
Source
Thrown at physics/potential_energy.py:51
"""
>>> potential_energy(10,10)
980.665
>>> potential_energy(0,5)
0.0
>>> potential_energy(8,0)
0.0
>>> potential_energy(10,5)
490.3325
>>> potential_energy(0,0)
0.0
>>> potential_energy(2,8)
156.9064
>>> potential_energy(20,100)
19613.3
"""
if mass < 0:
# handling of negative values of mass
raise ValueError("The mass of a body cannot be negative")
if height < 0:
# handling of negative values of height
raise ValueError("The height above the ground cannot be negative")
return mass * g * height
if __name__ == "__main__":
from doctest import testmod
testmod(name="potential_energy")
View on GitHub (pinned to f5988cc097)
Solutions
- Pass a non-negative mass in kg: potential_energy(10, 5) -> 490.3325
- Replace sentinel masses (e.g. -1) with a validation step that rejects the record before calling
- If computing deltas, compute potential_energy on absolute masses and subtract the results instead of passing a negative delta mass
Example fix
# before potential_energy(-10, 5) # ValueError: The mass of a body cannot be negative # after potential_energy(10, 5)
Defensive patterns
Strategy: validation
Validate before calling
if mass < 0:
raise ValueError(f"mass must be >= 0, got {mass}")
potential_energy(mass, height) Try / catch
try:
potential_energy(mass, height)
except ValueError as e:
if "mass" in str(e):
raise ValueError(f"bad mass in payload: {mass}") from e
raise Prevention
- Mass check runs before height check — fix mass first if both are invalid
- Replace -1/None mass sentinels with explicit rejection upstream
When it happens
Trigger: potential_energy(-10, 5); any call with a negative first argument, e.g. mass loaded from a physics body whose serialization used -1 for unknown mass.
Common situations: Using sentinel values like -1 for missing mass; importing bodies from game engines where negative mass means 'static/infinite'; sign errors from mass deltas (rocket propellant consumed) fed as absolute mass.
Related errors
- Mass can not be negative
- Gravitational force can not be negative
- Distance can not be negative
- The length should be non-negative
- The height above the ground cannot be negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/86915b037449b574.
Report an issue: GitHub.