Textbooks/Engineering Programming With Python/Chapter 2Lite (plain text) version
2Values, types and formulas
Version 1 · Technically checked (automated checks only) · 5 source lessons · 8 practice items
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.
Explanation
This chapter is built from 5 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
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 full 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 full 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.
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.
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.
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
Interactive figure (online). Description: 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.
Interactive figure (online). Description: 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.
Interactive figure (online). Description: 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
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Studio
Code Lab
Add 0.1 to a total ten times and compare the result with 1.0 using == and math.isclose.
Open Code Lab →Equation Lab exploration
Equation Lab: Functions
Type a formula with powers and division, then predict its value before evaluating to check operator precedence.
Open Equation Lab: Functions →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- Trace this Python by hand: x = 8; x = x + 1; x = x * 4; x = x - 20; print(x). What number is printed?
- Which program raises a NameError?
- x = 3 then print(x)
- print(y) then y = 3
- z = 3 then z = z + 1
- count = 0, then count += 1 runs 3 times, then count = count * 2 runs once. What is count?
- A machine makes 26 parts and packs them in boxes of 12. What does Python give for 26 // 12 (full boxes)? (parts)
- reading = "23.5". Which line gives the number 23.9?
- reading + 0.4
- float(reading) + 0.4
- int(reading) + 0.4
- Which test is the right way to check that a computed voltage v is 3.3 V?
- v == 3.3
- abs(v - 3.3) < 0.001
- v = 3.3
- A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts? (mV)
- What does Python give for -3 ** 2?
- 9
- -9
- An error
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 verified videos. Nothing loads from YouTube until you press play.
- Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data (Corey Schafer)
- Floating Point Numbers - Computerphile (Computerphile)
Chapter 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.
- 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.
- 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.
- Operator precedence
- Python evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything.
- 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.
Definitions from the 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
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
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 source 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.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.