Values, variables and expressions
Your first engineering calculations in Python: numbers, text, lists, the math module and the surprising truth about decimals.
35 min · Self-paced · Free
Why engineers program
Engineers spend a surprising amount of time calculating: the current through a resistor, the stress in a bracket, the average of a hundred sensor readings. A calculator is fine for one answer. But when the same calculation must be repeated for many values, checked, shared with a teammate, and rerun next week with new data, a short program is faster and far less error-prone. Python is a popular language for this work because it is readable, free, and has a huge collection of scientific tools built on top of it.
You can follow this lesson with Python 3 installed on a computer, or in any free online Python environment. Type the examples yourself rather than copying them — typing makes you notice the details.
Your first program
print("Hello, engineer!")print is a function: a named piece of code that does a job. You call it by writing its name followed by parentheses containing its input. Text in quotes is called a string. When you run this, Python displays:
Hello, engineer!Variables: naming values
A variable is a name attached to a value. You create one with =, which in Python means "store the value on the right under the name on the left" — not "is equal to" in the mathematical sense.
voltage = 9.0 # volts
resistance = 450.0 # ohms
current = voltage / resistance
print(current)Output:
0.02This is Ohm's law, I = V / R: 9 volts across 450 ohms drives 0.02 amps. Everything after a # is a comment. Python ignores comments; they are for people. Writing the unit next to each value is an excellent habit. Many real engineering failures have come from mixing up units, and a comment costs nothing.
Good variable names describe what they hold. current is clearer than c, and motor_speed_rpm is clearer still. Python names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive: Voltage and voltage are different variables.
Numbers and arithmetic
Python has two main kinds of number. Integers (int) are whole numbers like 3 or -12. Floating-point numbers (float) have a decimal point, like 3.0 or 0.02. The arithmetic operators are:
print(7 / 2) # division: 3.5
print(7 // 2) # floor division (whole part): 3
print(7 % 2) # remainder: 1
print(2 ** 10) # power: 1024Python follows the usual order of operations — powers first, then multiplication and division, then addition and subtraction — and parentheses override it. When in doubt, add parentheses: they make your intent obvious to the next reader.
Decimals are approximate
Try this:
print(0.1 + 0.2)The output is:
0.30000000000000004This is not a bug in Python. Computers store floats in binary, and most decimal fractions — including 0.1 — cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimal. The stored value is extremely close but not exact, and tiny differences can show up. The same thing happens in almost every programming language.
The practical lesson for engineers: never test floats for exact equality. Instead, ask whether two values are close enough:
import math
print(math.isclose(0.1 + 0.2, 0.3)) # TrueFormatting output
Raw numbers with many digits are hard to read. An f-string — a string with an f before the opening quote — lets you insert values and control their format:
current = 9.0 / 450.0
print(f"Current: {current * 1000:.1f} mA")Output:
Current: 20.0 mAInside the braces is any expression; :.1f means "show it as a decimal with one digit after the point". Reporting a sensible number of digits is part of communicating honestly: printing 20.000000 mA suggests a precision your measurement probably does not have.
Strings
Strings hold text. You can join them with +, find their length with len, and change them with methods such as .upper():
name = "servo"
print(name.upper()) # SERVO
print(len(name)) # 5
print(name + "-01") # servo-01A common surprise: "3" + "4" is "34", because joining two strings sticks them together. To do arithmetic on text that contains a number — for example, a value read from a file — convert it first with int("42") or float("2.5").
Lists
A list holds several values in order, inside square brackets. Lists are how you will handle sets of measurements.
readings = [20.2, 20.4, 19.8, 20.0] # temperatures in °C
average = sum(readings) / len(readings)
print(f"Average: {average:.2f} °C") # Average: 20.10 °C
print(readings[0]) # first item: 20.2
print(readings[-1]) # last item: 20.0
print(max(readings)) # 20.4
readings.append(20.6) # add a new reading at the end
print(len(readings)) # 5Notice that the first item is at position 0, not 1. Python, like most programming languages, counts positions (called indices) from zero. Negative indices count from the end.
The math module
Python's built-in math module provides square roots, π, trigonometry and much more. Import it once at the top of your program:
import math
print(math.sqrt(2)) # 1.4142135623730951
print(math.pi) # 3.141592653589793
print(math.cos(math.radians(60))) # 0.5000000000000001Two things to notice. First, the trigonometry functions use radians, so convert degrees with math.radians. Writing math.cos(60) computes the cosine of 60 radians, which is about −0.952 — a silent, plausible-looking mistake. Second, the cosine of 60° prints as 0.5000000000000001 rather than 0.5, for the same floating-point reason you saw earlier.
Worked example: one link of a robot arm
The tip of a 10 cm link rotated 30° from horizontal is at (L · cos θ, L · sin θ):
import math
length_cm = 10.0
angle_deg = 30.0
angle = math.radians(angle_deg)
x = length_cm * math.cos(angle)
y = length_cm * math.sin(angle)
print(f"Tip at ({x:.2f}, {y:.2f}) cm")Output:
Tip at (8.66, 5.00) cmThis is exactly the calculation from the Robotics Foundations lesson on coordinates — now in a form you can rerun for any length and angle in a second.
Knowledge check
Check your understanding
Go further
- The Python Tutorial (official documentation) ↗
The official, free tutorial from the Python developers. Sections 3 to 5 cover the material in this module in more depth.
Sign in to track your progress. Reading is free without an account.