Data Analysis for Engineers/Module 1

Module 1 · Section 5 of 10

Lesson 1.4 - Functions

Target: ~9 min read - 20 min hands-on

Overview

A function packages a calculation so you can reuse it with different inputs without retyping the formula. We'll define functions with def, use default parameter values for things that rarely change, and return multiple values at once.

Mental model: a function is a formula you write once and trust forever. Once verified against a hand calculation, you can call it a thousand times across a thousand components, and only your inputs - not the formula - could be a source of error.

Why This Matters (PH Context)

This pattern - write one verified function, run it across many components, feeders, or duty points - is how junior engineers at PH firms speed up preliminary sizing before a full analysis package is used for the final design.

Code-Along

# Lesson 1.4 - Functions

# 'def name(params):' defines a reusable function. The """...""" line right
# after is the docstring - a short description of what the function does.

def power_dissipated(voltage_V, resistance_ohm):
    """[Electrical] resistive power P = V^2 / R, in watts."""
    return voltage_V ** 2 / resistance_ohm      # ** is exponent; return hands a value back


def voltage_divider(vin_V, r1_ohm, r2_ohm):
    """[Electrical] return (output voltage across r2, loop current in A)."""
    current_A = vin_V / (r1_ohm + r2_ohm)
    return current_A * r2_ohm, current_A        # returning two values = a tuple


def pump_hydraulic_power(flow_m3s, head_m, rho=998.0):
    """[Mechanical/Chemical] useful hydraulic power (W). Default rho = water."""
    # rho=998.0 is a DEFAULT: callers can omit it and get water automatically
    return rho * 9.81 * flow_m3s * head_m


# Call a function by name, arguments in parentheses
print("P across 220 ohm at 12 V:", round(power_dissipated(12, 220), 3), "W")

# Unpack the returned tuple into two names at once
vout, i = voltage_divider(9.0, 1000, 2200)
print(f"Divider output: {vout:.2f} V at {i * 1000:.2f} mA")   # *1000: A -> mA

print("Pump hydraulic power:", round(pump_hydraulic_power(0.01, 20), 1), "W")

# The real payoff: write/verify the formula ONCE, then run it across many inputs
print("\nPower dissipation across a resistor bank at 24 V:")
for r in [100, 220, 470, 1000, 2200]:
    print(f"  {r:>5} ohm -> {power_dissipated(24, r):6.2f} W")   # {:>5} = right-align, width 5

Expected output:

P across 220 ohm at 12 V: 0.655 W
Divider output: 6.19 V at 2.81 mA
Pump hydraulic power: 1958.1 W

Power dissipation across a resistor bank at 24 V:
    100 ohm ->   5.76 W
    220 ohm ->   2.62 W
    470 ohm ->   1.23 W
   1000 ohm ->   0.58 W
   2200 ohm ->   0.26 W

Practice Exercises

  1. [Civil] Write beam_midspan_deflection(w_N_per_m, L_m, E_Pa, I_m4) returning 5 * w * L**4 / (384 * E * I). Test with w=2500, L=6, E=200e9, I=8.5e-6.
  2. [Chemical] Modify pump_hydraulic_power to also return the shaft power given an efficiency argument (default 0.65). Return two values.
  3. [Industrial] Write line_yield(good_units, total_units) returning the first-pass yield as a percentage. Test with 4720 / 5000.
# Try the practice exercises here

Knowledge Check

  1. What keyword defines a function in Python?
  2. What is a default parameter useful for?
  3. Can a Python function return more than one value?
Answer key
  1. def
  2. Providing a sensible fallback value for an input that rarely changes
  3. Yes, using a comma-separated return

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