Skip to content

Commit ea275fc

Browse files
committed
feat: Add mass_to_moles and moles_to_molecules conversions to molecular_chemistry.py
1 parent e3b01ec commit ea275fc

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

conversions/molecular_chemistry.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
* moles_to_pressure
55
* moles_to_volume
66
* pressure_and_volume_to_temperature
7+
* mass_to_moles
8+
* moles_to_molecules
79
"""
810

911

@@ -85,7 +87,45 @@ def pressure_and_volume_to_temperature(
8587
return round(float((pressure * volume) / (0.0821 * moles)))
8688

8789

90+
def mass_to_moles(mass: float, molar_mass: float) -> float:
91+
"""
92+
Convert mass of a substance to moles.
93+
Mass is taken in grams.
94+
Molar mass is taken in grams per mole (g/mol).
95+
96+
Wikipedia reference: https://en.wikipedia.org/wiki/Mole_(unit)
97+
98+
>>> mass_to_moles(36.03, 18.015)
99+
2.0
100+
>>> mass_to_moles(11.0, 44.01)
101+
0.25
102+
"""
103+
if molar_mass <= 0:
104+
raise ValueError("Molar mass must be greater than zero.")
105+
if mass < 0:
106+
raise ValueError("Mass cannot be negative.")
107+
108+
return round(float(mass / molar_mass), 2)
109+
110+
111+
def moles_to_molecules(moles: float) -> float:
112+
"""
113+
Convert moles of a substance to total molecules using Avogadro's constant.
114+
115+
Wikipedia reference: https://en.wikipedia.org/wiki/Avogadro_constant
116+
117+
>>> moles_to_molecules(2)
118+
1.2044e+24
119+
>>> moles_to_molecules(0.5)
120+
3.011e+23
121+
"""
122+
if moles < 0:
123+
raise ValueError("Moles cannot be negative.")
124+
125+
return float(f"{moles * 6.022e23:.4e}")
126+
127+
88128
if __name__ == "__main__":
89129
import doctest
90130

91-
doctest.testmod()
131+
doctest.testmod()

0 commit comments

Comments
 (0)