Python Programming
Python for Engineering Calculations
Python is a general-purpose language that engineers use to turn formulas and measured data into numbers. Typical jobs include sizing a pipe, converting a column of sensor readings, or checking a hand calculation. A small core of the language is enough to start: arithmetic with the right operators, arrays from the NumPy library for whole data sets, and functions and loops for repeated work. This lesson covers that core. It also covers the mistakes that most often give wrong numbers without any error message.
Numbers, operators and the math module
Python stores whole numbers as int and decimal numbers as float. Arithmetic follows the usual precedence. Exponentiation is evaluated before multiplication and division.
Operator | Meaning | Example | Result |
|---|---|---|---|
** | power | 2.5**2 | 6.25 |
/ | true division | 7 / 4 | 1.75 |
// | floor division | 7 // 4 | 1 |
% | remainder | 7 % 4 | 3 |
Functions such as square roots, and constants such as π, come from the math module:
import math
d = 0.025 # pipe inner diameter, m
A = math.pi * d**2 / 4 # flow area, m^2
print(A) # about 4.909e-04Arrays and indexing
A Python list holds values in order, but arithmetic on a list does not act on its elements. The NumPy library supplies arrays for that. An array supports a vectorized operation: one expression applied to every element at once, without writing a loop.
import numpy as np
p_kPa = np.array([101.3, 98.7, 95.2, 92.8, 90.1]) # pressure along a duct
p_Pa = p_kPa * 1000 # every element multipliedThe same expression means different things for a list and an array:
Expression | List x = [1.0, 2.0] | Array x = np.array([1.0, 2.0]) |
|---|---|---|
x * 2 | [1.0, 2.0, 1.0, 2.0] (repeated) | array([2., 4.]) |
x + x | [1.0, 2.0, 1.0, 2.0] (joined) | array([2., 4.]) |
x * 0.5 | TypeError | array([0.5, 1. ]) |
Python uses zero-based indexing: the first element is x[0] and the last is x[-1]. A slice x[start:stop] selects elements from start up to, but excluding, stop. For integer bounds satisfying 0≤start≤stop≤len(x), its number of elements is
For the pressure array, p_kPa[1:4] is array([98.7, 95.2, 92.8]). That is indices 1, 2 and 3: three values. Python clips slice bounds past the end, so p_kPa[2:10] contains only three values, at indices 2, 3 and 4. If the start exceeds the stop, as in p_kPa[3:1], this slice is empty.
Functions and loops
A function packages a formula so you can reuse and test it. For example, the Reynolds number of pipe flow is
In Python, this formula becomes:
def reynolds(rho, v, D, mu):
"""Reynolds number for pipe flow; SI inputs."""
return rho * v * D / mu
print(round(reynolds(998, 1.2, 0.05, 1.0e-3))) # 59880The body uses only arithmetic operators. So if you pass an array of speeds as v, the same function returns an array of Reynolds numbers.
A for loop repeats a block of code, usually over range(n). This produces the integers 0,1,…,n−1, so it stops one short of n. Use a loop when each step depends on the previous one, such as in a time-stepping simulation. When each element is computed independently, vectorized array expressions are often shorter and faster than an explicit Python loop.
h = 10.0 # tank level, m
for step in range(3):
h = h - 0.1 * h # level falls 10 % per step
print(h) # about 7.29What to remember
- ** is the power operator; ^ is not.
- / always gives a float; // rounds down to a whole number.
- Use NumPy arrays for element-by-element arithmetic; lists repeat or join instead.
- Indexing starts at 0. A slice x[start:stop] excludes stop and has stop - start elements when 0≤start≤stop≤len(x). Bounds past the end are clipped; a start greater than the stop gives an empty slice.
- Put formulas in functions. Use loops for steps that depend on earlier ones.
Example: Processing tensile-test data with NumPy
A tensile test on an aluminium-alloy rod gives five readings. The rod has a diameter of 10.0 mm and a gauge length of 50.0 mm. You load the readings as NumPy arrays:
import numpy as np
F = np.array([0.0, 5.0, 10.0, 15.0, 20.0]) # load, kN
dL = np.array([0.0, 0.045, 0.091, 0.137, 0.182]) # extension, mmAll readings lie in the elastic range.
a) Compute the cross-sectional area in m² and an array sigma of engineering stress in MPa. What is the stress at the 15 kN reading?
The area of a circular section is A=πd2/4. In SI units, the code is A = np.pi * 0.010**2 / 4, which gives
Stress is force divided by area. To get MPa, convert kN to N, divide by the area to get Pa, then divide by 106. One vectorized line does all of this: sigma = F * 1e3 / A / 1e6. NumPy applies it to every element. Rounded to two decimal places, the stresses are
The 15 kN reading is the fourth value, which is index ________. So sigma[3] is approximately 190.99 MPa, or 191.0 MPa to one decimal place.
b) Compute an array eps of engineering strain. Report the strain at the last reading using a negative index.
Strain is extension divided by gauge length. Both are in mm, so strain is dimensionless: eps = dL / 50.0.
eps[-1] is the last element: ε=0.182/50.0=3.64×10−3. A negative index counts from the end. So eps[-1] still picks the final reading if more readings are appended later.
c) Estimate Young's modulus E from the slope between the second reading and the last reading. Give E in GPa.
The second reading has index ________ and the last has index −1. In the elastic range σ=Eε, so E is the slope of stress against strain. The code is E = (sigma[-1] - sigma[1]) / (eps[-1] - eps[1]). This uses the unrounded array values and returns the modulus in MPa:
Divide the code result by ________ to convert MPa to GPa. Writing sigma[2] for the second reading would select the third value. That is a one-based counting slip.
d) A colleague stores the loads as a plain list, F_list = [0.0, 5.0, 10.0, 15.0, 20.0], and writes F_list * 1e3. What happens, and how do you fix it?
Multiplying a list by a number does not scale its elements. A list times an integer repeats the list. A list times a float such as 1e3 is not defined, so Python raises TypeError: can't multiply sequence by non-int of type 'float'.
The quieter danger is F_list * 1000. With an integer, it runs without error and returns a 5000-element list of repeated loads. Repetition changes the number and meaning of the readings, and a total cannot reveal the mistake: for any nonnegative integer factor k, k copies of the list always sum to k times the original total, exactly matching the total of the correctly scaled loads. Here, the original loads sum to ________, so both totals are 1000×50=50000. A sum check therefore cannot distinguish repetition from elementwise scaling; check the number of readings and their individual values.
The fix is to convert the list first with F = np.array(F_list). Then F * 1e3 multiplies every element and returns array([0., 5000., 10000., 15000., 20000.]), the five loads in N.
A cooling model in a Python script updates a part's temperature T (°C) and the elapsed time t (min) inside a while loop:
T = 340.0
t = 0
while T > 40.0:
T = T - (T - 20.0) / 2
t = t + 5
print(T, t)Trace the loop by hand and complete the table. Each pass means one full run of the two indented lines. Type numbers only, without units.
| Quantity | Value |
| T after pass 1 (°C) | |
| T after pass 2 (°C) | |
| Number of passes through the loop body | |
| Printed value of T (°C) | |
| Printed value of t (min) |
A thermocouple logs the temperature of a heated block every minute:
import numpy as np
T = np.array([20.0, 35.5, 48.2, 59.0, 66.4, 71.9]) # degrees C
warm = T[2:5]Which values does warm contain?