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 π\pi, come from the math module:


Python
import math
d = 0.025                  # pipe inner diameter, m
A = math.pi * d**2 / 4     # flow area, m^2
print(A)                   # about 4.909e-04



Arrays 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.


Python
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 multiplied


The 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)0 \le \text{start} \le \text{stop} \le \text{len}(x), its number of elements is


n=stop−startn = \text{stop} - \text{start}


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


Re=ρvDμRe = \frac{\rho v D}{\mu}


In Python, this formula becomes:


Python
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)))   # 59880


The 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−10, 1, \dots, n-1, so it stops one short of nn. 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.


Python
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.29


What 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)0 \le \text{start} \le \text{stop} \le \text{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:


Python
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, mm


All 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/4A = \pi d^2/4. In SI units, the code is A = np.pi * 0.010**2 / 4, which gives


A=π(0.010 m)24≈7.854×10−5 m2A = \frac{\pi (0.010\ \text{m})^2}{4} \approx 7.854 \times 10^{-5}\ \text{m}^2


Stress is force divided by area. To get MPa, convert kN to N, divide by the area to get Pa, then divide by 10610^6. 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


σ≈[0, 63.66, 127.32, 190.99, 254.65] MPa\sigma \approx [0,\ 63.66,\ 127.32,\ 190.99,\ 254.65]\ \text{MPa}


The 15 kN reading is the fourth value, which is index ________. So sigma[3] is approximately 190.99 MPa190.99\ \text{MPa}, or 191.0 MPa191.0\ \text{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.


ε=[0, 9.00×10−4, 1.82×10−3, 2.74×10−3, 3.64×10−3]\varepsilon = [0,\ 9.00\times10^{-4},\ 1.82\times10^{-3},\ 2.74\times10^{-3},\ 3.64\times10^{-3}]


eps[-1] is the last element: ε=0.182/50.0=3.64×10−3\varepsilon = 0.182/50.0 = 3.64 \times 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 EE from the slope between the second reading and the last reading. Give EE in GPa.


The second reading has index ________ and the last has index −1-1. In the elastic range σ=Eε\sigma = E\varepsilon, so EE 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:


E=σlast−σsecondεlast−εsecond≈254.647909−63.6619773.64×10−3−9.00×10−4 MPa≈69702.8948 MPa≈69.7 GPa\begin{aligned} E &= \frac{\sigma_{\text{last}}-\sigma_{\text{second}}}{\varepsilon_{\text{last}}-\varepsilon_{\text{second}}} \\ &\approx \frac{254.647909 - 63.661977}{3.64\times10^{-3} - 9.00\times10^{-4}}\ \text{MPa} \\ &\approx 69702.8948\ \text{MPa} \\ &\approx 69.7\ \text{GPa} \end{aligned}


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 kk, kk copies of the list always sum to kk 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=500001000 \times 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 vehicle of mass m=1200m = 1200 kg moves at v=3.0v = 3.0 m/s. Its kinetic energy is KE=12mv2KE = \tfrac{1}{2} m v^2. With m = 1200 and v = 3.0 already defined, which line of Python computes KEKE correctly in joules?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A cooling model in a Python script updates a part's temperature T (°C) and the elapsed time t (min) inside a while loop:


Python
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.

QuantityValue
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)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A thermocouple logs the temperature of a heated block every minute:


Python
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?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors