Data Analysis for Engineers/Module 1

Module 1 · Section 8 of 10

Lesson 1.7 - Modules & the Standard Library

Target: ~8 min read - 15 min hands-on

Overview

Python ships with a large standard library. This lesson tours four modules you'll use constantly: math (functions and constants), os (file-path handling), json (structured data - common in configs and APIs), and datetime (dates/times, essential for maintenance intervals and time-series data in Module 2).

We also cover importing third-party libraries - Pandas, NumPy, Matplotlib - pre-loaded in this course's Pyodide environment.

Why This Matters (PH Context)

datetime becomes essential once you track calibration or maintenance intervals, or work with time-stamped plant data. json is increasingly how modern instruments, PLC gateways, and government open-data APIs exchange structured information.

Code-Along

# Lesson 1.7 - Modules and the standard library

import math                                   # numeric functions & constants
import json                                   # read/write structured data
from datetime import datetime, timedelta      # import specific names from a module

# --- math: [Electrical] add two AC currents given as phasors (magnitude, angle) ---
def phasor_to_rect(mag, ang_deg):
    a = math.radians(ang_deg)                 # degrees -> radians for trig
    return mag * math.cos(a), mag * math.sin(a)   # polar (mag, angle) -> (x, y)

i1x, i1y = phasor_to_rect(10, 0)
i2x, i2y = phasor_to_rect(6, -120)
rx, ry = i1x + i2x, i1y + i2y                 # add the two vectors component-wise
# hypot(x, y) = sqrt(x^2 + y^2); atan2(y, x) recovers the angle (radians)
print(f"Resultant current: {math.hypot(rx, ry):.2f} A at {math.degrees(math.atan2(ry, rx)):.1f} deg")

# --- json: [Chemical] a nested dict is exactly the shape of a JSON object ---
recipe = {
    "product": "Batch 22 - resin",
    "charge_kg": {"monomer": 120, "solvent": 45, "initiator": 0.8},   # nested dict
    "setpoint_C": 82,
    "hold_minutes": 90,
}
recipe_json = json.dumps(recipe, indent=2)    # dict -> JSON text (indent=2 = pretty)
print("\n" + recipe_json)
# json.loads() parses JSON text back into Python dicts/lists; then index into it
print("Solvent charge:", json.loads(recipe_json)["charge_kg"]["solvent"], "kg")

# --- datetime: [Industrial] date arithmetic with timedelta ---
last_cal = datetime(2026, 1, 15)              # year, month, day
next_cal = last_cal + timedelta(days=180)     # add a duration -> a new date
print(f"\nLast calibration: {last_cal.date()}  ->  next due: {next_cal.date()}")
print("Next due on a:", next_cal.strftime("%A"))   # %A = full weekday name

Expected output (abridged):

Resultant current: 8.72 A at -36.6 deg

{
  "product": "Batch 22 - resin",
  ...
}
Solvent charge: 45 kg

Last calibration: 2026-01-15  ->  next due: 2026-07-14
Next due on a: Tuesday

Practice Exercises

  1. [Mechanical] Use math to compute the resultant magnitude and angle of two perpendicular forces, Fx = 120 N and Fy = 90 N.
  2. [Computer] Create a dict describing an API service (name, version, list of endpoints, rate limit), then convert it to JSON with json.dumps().
  3. [Civil] Given datetime(2026, 6, 1), compute the date exactly 45 days later, printed as "Month Day, Year" via strftime.
# Try the practice exercises here

Knowledge Check

  1. Which module provides sqrt, sin, cos, hypot, and the constant pi?
  2. What is json most useful for in engineering workflows?
  3. What does timedelta(days=180) represent?
Answer key
  1. math
  2. Structured data exchange (configs, recipes, APIs, instrument payloads)
  3. A duration of 180 days

8 / 63 sections · Course home · Join the coaching cohort