TheAlgorithms/Python · error · Exception

Molar mass cannot be less than or equal to 0 kg/mol

Error message

Molar mass cannot be less than or equal to 0 kg/mol

What it means

Raised by rms_speed_of_molecule(temperature, molar_mass) when molar_mass <= 0, guarding the division and square root in v = sqrt(3*R*T/M). Zero is also rejected (unlike temperature, where 0 K is fine). Like its sibling check it raises a bare built-in Exception, so 'except ValueError' will not catch it.

Source

Thrown at physics/rms_speed_of_molecule.py:36

way, which means that the average velocity for a collection of gas particles equals
zero; as this value is unhelpful, the average of velocities can be determined using an
alternative method.
"""

UNIVERSAL_GAS_CONSTANT = 8.3144598


def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float:
    """
    >>> rms_speed_of_molecule(100, 2)
    35.315279554323226
    >>> rms_speed_of_molecule(273, 12)
    23.821458421977443
    """
    if temperature < 0:
        raise Exception("Temperature cannot be less than 0 K")
    if molar_mass <= 0:
        raise Exception("Molar mass cannot be less than or equal to 0 kg/mol")
    else:
        return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5


if __name__ == "__main__":
    import doctest

    # run doctest
    doctest.testmod()

    # example
    temperature = 300
    molar_mass = 28
    vrms = rms_speed_of_molecule(temperature, molar_mass)
    print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass molar mass in kg/mol, strictly positive (e.g. 0.028 for N2, 0.002 for H2 as in the doctests)
  2. Make gas-property lookups raise KeyError for unknown gases instead of defaulting to 0
  3. Pre-check molar_mass > 0 and catch Exception (not ValueError) around this call

Example fix

# before
MOLAR_MASS = {'co2': 0.044, 'n2': 0.028}
rms_speed_of_molecule(300, MOLAR_MASS.get('o2', 0))  # unknown gas -> 0
# Exception: Molar mass cannot be less than or equal to 0 kg/mol

# after
MOLAR_MASS = {'co2': 0.044, 'n2': 0.028, 'o2': 0.032}
rms_speed_of_molecule(300, MOLAR_MASS['o2'])
Defensive patterns

Strategy: try-catch

Validate before calling

if molar_mass <= 0:
    raise ValueError(f"molar mass must be > 0 kg/mol, got {molar_mass}")
rms_speed_of_molecule(temperature, molar_mass)

Try / catch

try:
    v = rms_speed_of_molecule(temperature, molar_mass)
except Exception as e:  # bare Exception, not ValueError
    if "Molar mass" in str(e):
        raise ValueError("gas lookup returned invalid molar mass") from e
    raise

Prevention

When it happens

Trigger: rms_speed_of_molecule(300, 0) — zero molar mass; rms_speed_of_molecule(300, -0.032) — negative molar mass, e.g. from a bad lookup or a sign typo; molar-mass tables keyed by gas name returning 0 for an unknown gas.

Common situations: Unknown gas falling through a dict lookup to a 0 default; unit mix-ups between g/mol and kg/mol that push values through lossy conversions; per-particle mass passed instead of molar mass.

Related errors


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