Lite / Textbooks / Engineering Programming With Python / Chapter 2
2. Values, types and formulas
Introduction
A variable is a name stuck on a value, and the value has a type: whole number, decimal, text or list. Types decide what operations mean: 7 // 2 is 3, "7" + "2" is "72". Decimals are stored in binary, so 0.1 + 0.2 is not quite 0.3, and engineers compare floats with a tolerance. With that settled, turning a formula into code is careful work with brackets, units and the order of operations.
Figure 2.1. Floats are close, not exact (described in words)
A Python prompt shows 0.1 + 0.2 evaluating to 0.30000000000000004. The error is about 5.6e-17, so math.isclose(0.1 + 0.2, 0.3) returns True and is the right way to compare.
Explanation
Built from 5 School lessons. Each part is the lesson's own explanation.
2.1 How the interpreter reads your program
You compute current = voltage / resistance, then change the voltage. Does current change too?
One line at a time, top to bottom
The interpreter starts at line 1. For an assignment it works out the right-hand side using the values that exist right now, then stores the result under the name on the left. Then it moves to the next line. Nothing goes back up unless a loop or function tells it to.
Assignment is a snapshot
voltage_v = 12
resistance_ohm = 48
current_a = voltage_v / resistance_ohm
print(current_a) # 0.25
voltage_v = 24 # changing it now does not update current_a
print(current_a) # still 0.25To get the new current you must run the calculation again.
Names must exist before you use them
If line 2 uses resistance_ohm but line 3 is where it is created, Python stops at line 2 with NameError: name 'resistance_ohm' is not defined. The fix is to move the assignment above the line that needs it. A typo in a name gives the same error.
Common mix-ups
Variables update automatically when the values they were made from change, like spreadsheet cells.
✓ A variable holds the value from when its line ran. Recompute it to update it.= in Python means 'is equal to'.
✓ = means 'store'. Equality is tested with ==.
Open the Lite lesson: How the interpreter reads your program
2.2 Variables that track a changing machine
A robot adds speed × time to its distance fifty times a second. How does one variable keep track of all that?
Names that explain themselves
distance_m, speed_m_per_s, parts_made say what they are and in which unit. Python names use letters, digits and underscores, cannot start with a digit and are case-sensitive (Speed and speed are different). Clear names are the cheapest documentation there is.
Updating from the old value
parts_made = parts_made + 1 reads the old value, adds 1 and stores the result: a counter. distance_m = distance_m + speed_m_per_s * dt_s is a running total. The short form parts_made += 1 does the same. Both need a starting value first, such as parts_made = 0.
Swapping without losing data
left_c, right_c = 31.5, 29.0
left_c, right_c = right_c, left_c
print(left_c, right_c) # 29.0 31.5Python evaluates the whole right side first, then assigns, so nothing is overwritten too early. The step-by-step version needs a spare: spare_c = left_c, then left_c = right_c, then right_c = spare_c.
Common mix-ups
a = b then b = a swaps two values.
✓ The first line overwrites a, so its old value is gone. Use a spare or a, b = b, a.Short names like x and t make code tidier.
✓ In engineering code, names with units (time_s, temp_c) prevent mistakes that cost far more than a few keystrokes.
Open the Lite lesson: Variables that track a changing machine
2.3 int, float, str and list
A sensor file says "23.5". Add 0.4 and Python refuses. Why is a number in quotes not a number?
Five types you will use every day
int: whole numbers, 135. float: numbers with a decimal point, 23.5. str: text in quotes, "23.5". bool: True or False, the result of a comparison. list: an ordered collection, [21.5, 22.0, 22.4]. Ask type(x) to check.
Three kinds of division
seconds = 135
minutes = seconds // 60 # 2 (floor division)
leftover_s = seconds % 60 # 15 (remainder)
print(f"{minutes} min {leftover_s} s")
print(7 / 2) # 3.5 (always a float)// and % together split a quantity into whole units and what is left over: seconds into minutes, parts into boxes.
Text is not a number until you convert it
"23.5" + 0.4 raises a TypeError. float("23.5") + 0.4 gives 23.9. int("42") gives 42, but int("4.2") raises a ValueError, and int(9.99) chops to 9, it does not round. With strings, + joins text: "7" + "2" is "72".
Common mix-ups
int(9.99) rounds to 10.
✓ int() chops the fraction: int(9.99) is 9. Use round() to round./ gives an int when the answer is whole.
✓ In Python 3, / always gives a float: 6 / 3 is 2.0.
Open the Lite lesson: int, float, str and list
2.4 Why 0.1 + 0.2 is not 0.3
Ask Python whether 0.1 + 0.2 == 0.3 and it says False. Is your computer broken?
See it in code
import math
total = 0.1 + 0.2
print(total) # 0.30000000000000004
print(total == 0.3) # False
print(math.isclose(total, 0.3)) # True
print(abs(total - 0.3) < 1e-9) # TrueThe last two lines are how engineers compare measured or computed values: within a stated tolerance.
Errors can accumulate
One addition is off by about 10⁻¹⁷. Add 0.1 a million times and the errors can add up to something you can see. A timer that does t = t + 0.1 every tick slowly drifts. The cure is to count whole ticks in an int and compute t = ticks * 0.1 when needed.
Practical rules
Never test floats with ==; use a tolerance that means something physically (1 mV, 0.01 °C). Keep money and counts in ints (pence, millimetres, ticks). Round only for display, with round() or an f-string such as f"{x:.2f}", not in the middle of a calculation.
Derivation: Why 0.1 cannot be written exactly in binary
In base 10, 1/3 = 0.333… never ends, because 3 does not divide any power of 10. A fraction ends in base 10 only if its denominator is built from 2s and 5s (the factors of 10).
In base 2, a fraction ends only if its denominator is a power of 2. 1/2 = 0.1₂ and 1/4 = 0.01₂ are exact, so 0.5 and 0.25 are stored perfectly.
0.1 = 1/10 = 1/(2 × 5). The factor 5 is not a power of 2, so in binary 0.1 repeats for ever: 0.000110011001100…₂.
A Python float keeps 53 binary digits, so it stores the nearest value it can: 0.1000000000000000055511151231257827… That error is tiny (about 5.6 × 10⁻¹⁸) but not zero.
0.1 + 0.2 adds two rounded values and rounds again. The result lands one step above the float nearest to 0.3, so
0.1 + 0.2 == 0.3is False whilemath.isclose(0.1 + 0.2, 0.3)is True.
Common mix-ups
0.1 + 0.2 != 0.3 means Python has a bug.
✓ It is how binary floating point works in almost every language. Python is doing exactly what IEEE 754 specifies.Floats are random or unreliable.
✓ Floats are deterministic and very accurate (about 16 significant digits). Only exact equality tests and long accumulations need care.
Open the Lite lesson: Why 0.1 + 0.2 is not 0.3
2.5 Translate a formula into Python
Two programs compute a voltage divider's output. One says 3.4 V, the other 2211 V. Which pair of brackets is missing?
Python's order of operations
- Brackets. 2. Powers
**(worked right to left). 3. Unary minus, so-3 ** 2is-9. 4.*,/,//,%from left to right. 5.+,-from left to right. When in doubt, add brackets: they cost nothing and show your intent.
A translation recipe
- Name each quantity with its unit:
mass_kg,speed_m_per_s. 2. Replace a fraction bar with/and wrap the whole top and bottom in brackets. 3. Write powers with**. 4. Run it with numbers you can check by hand.
mass_kg = 1.2
speed_m_per_s = 3
energy_j = 0.5 * mass_kg * speed_m_per_s ** 2
print(round(energy_j, 2)) # 5.4Units check and estimate
For E = ½mv²: kg × (m/s)² = kg·m²/s² = J, so the formula is consistent. Estimate: ½ × 1 × 3² ≈ 4.5, close to 5.4. If an answer is out by a factor of 1000 or has the wrong unit, a conversion or bracket is missing.
Derivation: Average speed is total distance over total time
A robot drives d₁ = 120 m in t₁ = 40 s, then d₂ = 80 m in t₂ = 60 s.
Average speed means one steady speed that covers the same total distance in the same total time: v = (d₁ + d₂) / (t₁ + t₂).
Substitute: v = (120 + 80) / (40 + 60) = 200 m / 100 s = 2.0 m/s.
Averaging the two speeds gives (3.0 + 1.33) / 2 ≈ 2.17 m/s, which is wrong because the robot spends longer on the slow leg.
In Python the brackets carry the fraction bar:
(d1_m + d2_m) / (t1_s + t2_s). Without them,d1_m + d2_m / t1_s + t2_sgives 120 + 2 + 60 = 182.0, with meaningless units.
Common mix-ups
Python works out a line from left to right, whatever the operators.
✓ Precedence comes first: ** before * and /, which come before + and −. Left to right only applies within the same level.Extra brackets are bad style.
✓ Brackets that show intent are good style in engineering code, especially around a whole numerator or denominator.
Open the Lite lesson: Translate a formula into Python
Worked examples
How the interpreter reads your program: example 1
Trace: speed = 2; time = 5; distance = speed * time; speed = 3; print(distance).
Solution
speed 2 → time 5 → distance 10 → speed 3 → prints 10. distance was computed when speed was 2; the later change to speed does not affect it.
Variables that track a changing machine: example 1
distance_m = 0; speed 1.5 m/s for two steps of 2 s, then 0.5 m/s for one step of 2 s. Final distance?
Solution
0 + 1.5 × 2 = 3.0 → 3.0 + 1.5 × 2 = 6.0 → 6.0 + 0.5 × 2 = 7.0 m. This is the 'Odometer update' program; the tracer prints 7.0 m.
int, float, str and list: example 1
A process takes 7384 s. Write it as hours, minutes and seconds with // and %.
Solution
hours = 7384 // 3600 = 2; rest = 7384 % 3600 = 184; minutes = 184 // 60 = 3; seconds = 184 % 60 = 4. So 2 h 3 min 4 s. Check: 2 × 3600 + 3 × 60 + 4 = 7384.
Why 0.1 + 0.2 is not 0.3: example 1
A test asserts led_resistor(3.3, 2.0, 10) == 130 and fails. The function returns 129.99999999999997. Is the function wrong?
Solution
No. (3.3 − 2.0) is stored as 1.2999999999999998, and dividing by 0.01 gives 129.99999999999997. The test is wrong: write assert abs(led_resistor(3.3, 2.0, 10) - 130) < 1e-9, or a tolerance that matches the resistor's own precision.
Translate a formula into Python: example 1
Write F = C × 9/5 + 32 in Python and check it at 100 °C.
Solution
temp_f = temp_c * 9 / 5 + 32. Left to right: 100 × 9 = 900, / 5 = 180.0, + 32 = 212.0 °F, which is right for boiling water. temp_c * 9 / (5 + 32) would divide by 37 instead and give about 24.3.
Interactive figures, in words
Figure 2.2 from How the interpreter reads your program
Start with 'Battery runtime' and press 'Run next line' one line at a time, watching the variable table. Then try 'Odometer update' (predict distance_m before each step) and 'Used before it exists': which line fails, and why?
The program tracer shows a short Python program, highlights the line just run and lists every variable with its value and type after that line. For example, in 'Battery runtime', after line 3 the table shows capacity_mah 2000 (int), current_ma 250 (int), hours 8.0 (float). In 'Used before it exists', line 2 stops with a NameError because resistance_ohm is created only on line 3.
Figure 2.3 from int, float, str and list
Predict the value and type of each expression before you click it. Start with 7 / 2, 7 // 2 and 6 / 3, then the string ones. In 'Try your own numbers', find two numbers where // and / give the same value but different types.
The type inspector lists expressions with their Python results: 7 / 2 → 3.5 (float); 6 / 3 → 2.0 (float); 7 // 2 → 3 (int); 135 // 60 → 2 and 135 % 60 → 15 (int); "7" + "2" → '72' (str); "23.5" + 0.4 → TypeError; float("23.5") + 0.4 → 23.9; int("4.2") → ValueError; int(9.99) → 9. A second panel computes any two numbers with any operator and shows the result and its type.
Figure 2.4 from Why 0.1 + 0.2 is not 0.3
Add 0.1 one time, two times, three times… When does == first say False? Find a number of additions where == says True again. Then look at what Python really stores for 0.1, 0.5 and 0.25: which ones are exact?
The float explorer adds 0.1 to a total n times and prints the result as Python does: n = 1 gives 0.1, n = 2 gives 0.2, n = 3 gives 0.30000000000000004 (== 0.3 is False, math.isclose is True), n = 8 gives 0.7999999999999999. A second panel shows the exact stored values: 0.1 is 0.1000000000000000055511151231257827021181583404541015625, while 0.5 and 0.25 are exact.
Laboratory
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Code Lab (Studio)
Add 0.1 to a total ten times and compare the result with 1.0 using == and math.isclose.
Open on the full site - Equation Lab: Functions (Equation Lab exploration)
Type a formula with powers and division, then predict its value before evaluating to check operator precedence.
Open on the full site
Practice
Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.
- Trace this Python by hand: x = 8; x = x + 1; x = x * 4; x = x - 20; print(x). What number is printed?
Answer it in “How the interpreter reads your program” - Which program raises a NameError?
Answer it in “How the interpreter reads your program” - count = 0, then count += 1 runs 3 times, then count = count * 2 runs once. What is count?
Answer it in “Variables that track a changing machine” - A machine makes 26 parts and packs them in boxes of 12. What does Python give for 26 // 12 (full boxes)?
Answer it in “int, float, str and list” - reading = "23.5". Which line gives the number 23.9?
Answer it in “int, float, str and list” - Which test is the right way to check that a computed voltage v is 3.3 V?
Answer it in “Why 0.1 + 0.2 is not 0.3” - A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts?
Answer it in “Why 0.1 + 0.2 is not 0.3” - What does Python give for -3 ** 2?
Answer it in “Translate a formula into Python”
Engineering applications
Timers that drift
A loop that adds 0.1 seconds to a clock thousands of times slowly drifts, because 0.1 has no exact binary form. Counting whole ticks as integers and converting at the end avoids the error building up.
Readable formulas
Naming variables with their units, such as current_a and resistance_ohm, makes a formula check itself. If the line reads volts = current_a / resistance_ohm, the mistake is visible before it runs.
Watch (optional)
Streaming video uses a lot of data. Everything you need is in the text.
- “Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data” by Corey Schafer
- “Floating Point Numbers - Computerphile” by Computerphile
Summary
- A variable names a value; assignment replaces it, and updates such as count = count + 1 build on it.
- Types matter: int, float, str and list each define their own operations.
- Floats are binary approximations; compare them with a tolerance, never with ==.
- Precedence decides the order: -x**2 is -(x**2), so use brackets to say what you mean.
Glossary
- Variables and assignment
- An assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result. Field Guide
- int and float
- Python's int holds whole numbers of any size exactly; float holds real numbers approximately, in 64-bit binary floating point with about 15 to 16 significant digits. Field Guide
- Floating-point rounding and comparison
- Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable. Field Guide
- Operator precedence
- Python evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything. Field Guide
- Floor division and modulo
- a // b divides and rounds down to the nearest whole number; a % b gives the remainder, so that a == (a // b) * b + a % b always holds. Field Guide
Project: A units-safe calculator
Write a short program that reads a wheel diameter in millimetres and a speed in revolutions per minute, converts everything to SI units in one place, and prints the vehicle speed in metres per second and kilometres per hour. Include one check that uses a tolerance rather than ==.
Deliverables
- The program with units in every variable name
- Three test values worked by hand
- A note on where a float comparison could have gone wrong
Write it up on paper or in your own notes. Lite never stores what you write.
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- David Goldberg (1991). "What Every Computer Scientist Should Know About Floating-Point Arithmetic". ACM Computing Surveys 23(1), 5–48. doi:10.1145/103162.103163 Link
- Python Software Foundation. The Python Tutorial: Floating-Point Arithmetic: Issues and Limitations. Python Software Foundation. Link
Further reading from the lessons
- Python tutorial: numbers and text
The official tutorial's first look at numbers, strings and lists. - Floating-point arithmetic: issues and limitations
The official Python tutorial's own explanation of this exact surprise. - Python reference: operator precedence
The official table of which operators bind tighter.