Lesson 2 of 4
Do arithmetic with Python's operators, control the order of operations, compare values, and use the math module for scientific functions.
About 25 minutes
//, % and **and, or and notmath module for common calculationsAn expression is any piece of code that Python can work out to a single value, such as 2 + 3 or mass / volume. Expressions are built from values, variables and operators: symbols that perform an operation, like + for addition.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
// | Floor division (whole-number part) | 7 // 2 | 3 |
% | Remainder (modulo) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
// and % are a pair. // tells you how many whole times one number fits into another, and % tells you what is left over. For example, 130 minutes is 2 whole hours (130 // 60) and 10 minutes (130 % 60).
total_minutes = 130hours = total_minutes // 60minutes = total_minutes % 60print(hours, "h", minutes, "min")Python follows the same order of operations as mathematics. Powers are worked out first, then multiplication and division, then addition and subtraction. Operators with the same priority are worked out from left to right. Brackets override all of this: anything inside brackets is calculated first.
print(2 + 3 * 4) # multiplication firstprint((2 + 3) * 4) # brackets firstWhen you turn a scientific formula into code, add brackets wherever they make the meaning clearer, even if they aren't strictly needed. A common mistake is forgetting brackets around a denominator: a / b + c is not the same as a / (b + c).
The theoretical density of a crystal is (atoms per cell × molar mass) ÷ (unit cell volume × Avogadro's number). For copper, with the volume in cm³:
atoms_per_cell = 4molar_mass = 63.55 # g/molcell_volume = (3.615e-8) ** 3 # cm³ (3.615 Å = 3.615e-8 cm)avogadro = 6.022e23density = (atoms_per_cell * molar_mass) / (cell_volume * avogadro)print("Density:", round(density, 2), "g/cm³")The brackets make sure the whole top and the whole bottom of the fraction are calculated before dividing. The result is close to copper's measured density of 8.96 g/cm³.
Updating a variable based on its own value is so common that Python has shortcuts for it. total += 5 means exactly the same as total = total + 5.
| Shortcut | Same as |
|---|---|
x += 2 | x = x + 2 |
x -= 2 | x = x - 2 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
total_mass = 0.0total_mass += 12.5 # add the first sampletotal_mass += 8.3 # add the second sampleprint(total_mass)A comparison checks how two values relate and gives a Boolean result: True or False. Comparisons are how programs make decisions, which you will use in the Control Flow module.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 3 <= 2 | False |
melting_point = 1085 # °C, copperprint(melting_point > 1000)print(melting_point == 1000)= is not ==
= assigns a value to a variable. A double == asks whether two values are equal. Mixing them up is one of the most common beginner mistakes.The logical operators and, or and not combine Boolean values. and is True only if both sides are true; or is True if at least one side is true; not flips True to False and back.
density = 2.70 # g/cm³melting_point = 660 # °Cis_light = density < 5is_high_temperature = melting_point > 1000print(is_light and is_high_temperature)print(is_light or is_high_temperature)print(not is_light)Python has some numeric functions built in. abs() gives the absolute value, round() rounds, and min() and max() return the smallest and largest of several values.
print(abs(-3.2))print(round(2.71828, 3))print(min(660, 1085, 1538))print(max(660, 1085, 1538))For square roots, logarithms, trigonometry and constants such as π, use the math module. A module is a file of ready-made code. import math makes it available, and you then use its contents with a dot: math.sqrt(), math.pi.
import mathradius = 1.28e-8 # cm, atomic radius of copperatom_volume = 4 / 3 * math.pi * radius ** 3print(math.sqrt(16))print(round(math.pi, 4))print(atom_volume)| Function | What it does |
|---|---|
math.sqrt(x) | Square root |
math.exp(x) | e to the power of x |
math.log(x) | Natural logarithm (ln) |
math.log10(x) | Logarithm to base 10 |
math.sin(x), math.cos(x) | Trigonometry, with x in radians |
math.pi, math.e | The constants π and e |
Floating-point numbers are not exact
0.1 + 0.2 gives 0.30000000000000004. The error is tiny and doesn't matter for most scientific work, but it is why you should round numbers when displaying them, and avoid checking floats with ==.Choose an answer and press Check answer. You can retry as often as you like.