1.1
Your First Calculation: Molar Mass
A calculation you already know, handed to Python, and your first variables along the way.
In this unit you will:
- compute a molar mass with Python;
- create variables and use them in an expression;
- print a result and check it against a hand calculation.
Every chemist has computed a molar mass by hand: look up the atomic mass of each element, multiply it by the number of atoms of that element in the formula, and add the results. It is a small calculation, but it is exactly the kind of task computers do well: the same steps, repeated, without arithmetic slips. In this unit we hand that calculation to Python.
1.1.1The calculation by hand
For a compound that contains atoms of element , each with atomic mass , the molar mass is the sum over all the elements present:
For ethanol, C2H6O, Equation 1.1 gives = 2(12.011) + 6(1.008) + 1(15.999) = 46.069 g mol−1. Table 1.1 lists the atomic masses used throughout this volume.
| Element | Symbol | Atomic mass, (g mol−1) |
|---|---|---|
| Hydrogen | H | 1.008 |
| Carbon | C | 12.011 |
| Nitrogen | N | 14.007 |
| Oxygen | O | 15.999 |
1.1.2The same calculation in Python
Type the lines in Listing 1.1 into a Python prompt. If you have not installed Python yet, any online Python notebook will do; installation is covered in Unit 1.2.
# Atomic masses in g/mol
C = 12.011
H = 1.008
O = 15.999
M_ethanol = 2*C + 6*H + 1*O
print(M_ethanol)46.069
Lines 2–4 each create a variable: a name, such as C, attached to a value. Line 6 is Equation 1.1 written for ethanol, and line 7 prints the result. The output, 46.069, matches the hand calculation exactly.
Contribution of each element to the molar mass of ethanol, C2H6O (46.069 g mol−1). Carbon accounts for just over half.
Worked example 1.1: Glucose
Problem. Compute the molar mass of glucose, C6H12O6.
Solution. Reuse the variables from Listing 1.1 and change only the counts:
M_glucose = 6*C + 12*H + 6*O
print(M_glucose)180.156
Check. By hand: 6(12.011) + 12(1.008) + 6(15.999) = 72.066 + 12.096 + 95.994 = 180.156 g mol−1.
[Photo caption, for example: weighing a sample on an analytical balance. Credit: photographer or source.]
Writing 2C + 6H + O as you would on paper. Python reads 2C as a malformed number and stops with a SyntaxError. Always write the multiplication sign.
- A variable attaches a name to a value;
C = 12.011creates one. - Python evaluates an expression such as
2*C + 6*H + 1*Owith the usual order of operations. - Check every computed result against an estimate or a hand calculation.
Exercises
- Compute the molar mass of water, H2O.
- Add a variable for nitrogen from Table 1.1 and compute the molar mass of ammonia, NH3.
- Modify Listing 1.1 to compute the molar mass of acetic acid, C2H4O2.
Show answers
- 18.015 g mol−1
- 17.031 g mol−1
- 60.052 g mol−1
Found an error or have a question about this lesson? Let me know.
REVISIONS16 November 2026 · First published.