Engineering User-Defined Functions: Reliable Numerical Calculations

Engineering user-defined functions turn a mathematical relationship into a calculation you can reuse with different measurements. Their value comes from making the calculation's assumptions, units, and output explicit. Using Python 3, you will connect an engineering equation to a function that returns a useful numerical result. The focus is the reliability of the calculation, rather than the organization of a larger program.

Specify the calculation

Before writing code, establish a function contract: the inputs a function accepts, the conditions those inputs satisfy, and the result it returns. Units belong in this contract because a numerical value alone does not identify a physical quantity.


For example, suppose a pump delivers a steady volumetric flow against a pressure increase. Under the supplied model, its required input power is


Pin=Δp QηP_{\text{in}}=\frac{\Delta p\,Q}{\eta}


Here, Δp\Delta p is the pressure increase in pascals, QQ is the flow rate in cubic metres per second, and η\eta is the dimensionless pump efficiency expressed as a fraction. The resulting power is in watts because Pa⋅m3/s=W\text{Pa}\cdot\text{m}^3/\text{s}=\text{W}.


A suitable contract accepts nonnegative pressure and flow, with 0<η≤10<\eta\leq1. Assume all inputs are finite real numbers. Zero flow or zero pressure is allowed by this simplified model and produces zero power.


Input case

Contract decision

Reason

Efficiency between 0 and 1, inclusive of 1

Accept

The model permits a positive efficiency up to the ideal limit.

Efficiency equal to 0

Reject

The calculation would divide by zero.

Efficiency greater than 1

Reject

It falls outside the stated pump model.

Negative pressure increase or flow

Reject

This function covers the specified pumping direction.



Implement and return the result

The function below uses names that identify the expected units. It checks the input domain before evaluating the equation.


Python
def pump_input_power(flow_m3_s, pressure_pa, efficiency):
    if flow_m3_s < 0 or pressure_pa < 0:
        raise ValueError("Flow and pressure must be nonnegative.")
    if efficiency <= 0 or efficiency > 1:
        raise ValueError("Efficiency must be greater than 0 and at most 1.")

    hydraulic_power_w = pressure_pa * flow_m3_s
    input_power_w = hydraulic_power_w / efficiency
    return input_power_w


The intermediate quantities are local to this function call. They make the physical steps visible: first calculate the power transferred to the fluid, then account for efficiency. Each call evaluates these steps using its own supplied inputs.


A return value is the result a function passes back to the expression that called it. Returning power lets you store it, compare it, or use it in another calculation:


Python
power_w = pump_input_power(0.012, 150000.0, 0.75)
power_kw = power_w / 1000.0


For these inputs,


Pin=(150000)(0.012)0.75=2400 W=2.40 kWP_{\text{in}}=\frac{(150000)(0.012)}{0.75} =2400\ \text{W}=2.40\ \text{kW}



Check behavior against the contract

Check an ordinary valid input, an allowed boundary, and a rejected input. For this function, an ordinary case checks the arithmetic; zero flow checks an allowed boundary; zero efficiency checks rejection before division.


Also check how the result responds when one input changes while the others stay fixed. Doubling flow doubles the predicted power. Changing efficiency from 0.40 to 0.80 halves the predicted input power because efficiency appears in the denominator. These checks can expose an inverted formula even when a function runs without an error.


Keep unit conversion explicit. This function accepts cubic metres per second, so convert a measurement in litres per second before passing it in. A name such as flow_m3_s documents the convention, but Python does not automatically enforce physical units.


What to remember

  • State input units, allowed values, and output units before coding.
  • Translate the engineering equation using clear local quantities.
  • Return the numerical result so subsequent calculations can use it.
  • Check ordinary inputs, boundaries, and physically expected changes.

Example: Calculate Heater Energy with a User-Defined Function

An electric heater warms an aluminium component. Assume uniform temperature, constant specific heat capacity, and no heat loss. The required thermal energy is


E=mc(Tf−Ti)E=mc(T_f-T_i)


Use Python 3 to implement this calculation. The function must accept mass in kilograms, specific heat capacity in J/(kg·K), and initial and final temperatures in °C. It must return energy in kilojoules. Its contract requires positive mass, positive specific heat capacity, and a final temperature at least as high as the initial temperature. Assume all inputs are finite real numbers.


For the initial calculation, use m=2.40 kgm=2.40\ \text{kg}, c=9.00×102 J/(kg⋅K)c=9.00\times10^2\ \text{J/(kg·K)}, Ti=18.0 ∘CT_i=18.0\ ^\circ\text{C}, and Tf=68.0 ∘CT_f=68.0\ ^\circ\text{C}.


a) Write a function named heating_energy_kj that implements the contract and returns the required energy.


First reject values outside the stated input domain. Next calculate the temperature difference, multiply by mass and specific heat capacity to obtain joules, and divide by 1000 to return kilojoules. A temperature difference has the same numerical value in kelvins and degrees Celsius.


Python
def heating_energy_kj(mass_kg, specific_heat_j_kg_k,
                      initial_c, final_c):
    if mass_kg <= 0 or specific_heat_j_kg_k <= 0:
        raise ValueError("Mass and specific heat must be positive.")
    if final_c < initial_c:
        raise ValueError("Final temperature must not be lower.")

    temperature_rise_k = final_c - initial_c
    energy_j = mass_kg * specific_heat_j_kg_k * temperature_rise_k
    return energy_j / 1000.0


The function returns the energy rather than printing it, allowing the caller to store the result. Equal initial and final temperatures are permitted and produce 0.0 kJ.


b) Write a call for the initial component and calculate the returned value.


Pass each supplied quantity using the units required by the function. Assign the returned value to a variable that identifies its output unit:


Python
energy_kj = heating_energy_kj(2.40, 900.0, 18.0, 68.0)


The temperature rise is


ΔT=68.0−18.0=50.0 K\Delta T=68.0-18.0=50.0\ \text{K}


Substitute into the supplied energy relationship:


E=(2.40 kg)(900 J/(kg⋅K))(50.0 K)=108000 JE=(2.40\ \text{kg})(900\ \text{J/(kg·K)})(50.0\ \text{K}) =108000\ \text{J}


Convert to the required output unit:


E=1080001000=108 kJE=\frac{108000}{1000}=108\ \text{kJ}


The variable energy_kj therefore contains 108.0. The kilogram and kelvin units cancel within the product, leaving joules before the final conversion.


c) A second component has mass 3.60 kg and the same specific heat capacity and temperatures. Write another call, calculate its result, and determine the total energy for both components.


Reuse the same function with the new mass. Its local intermediate quantities are calculated afresh for this call, while the previously stored result remains available.


Python
second_energy_kj = heating_energy_kj(3.60, 900.0, 18.0, 68.0)
total_energy_kj = energy_kj + second_energy_kj


For the second component,


E2=(3.60)(900)(68.0−18.0)1000=162 kJE_2=\frac{(3.60)(900)(68.0-18.0)}{1000} =162\ \text{kJ}


Add the two returned energies:


Etotal=108+162=270 kJE_{\text{total}}=108+162=270\ \text{kJ}


The second mass is ________ times the first mass, and its required energy is also ________ times as large. This agrees with the proportional dependence on mass when specific heat capacity and temperature rise stay fixed. The second call returns 162.0 kJ, and the total is 270.0 kJ.

A Python 3 function calculates density from mass in kilograms and volume in cubic metres:


Python
def density(mass_kg, volume_m3):
    density_kg_m3 = mass_kg / volume_m3
    print(density_kg_m3)


The calling code must store the numerical density for a later calculation:


Python
rho = density(7.8, 0.001)


Which replacement for the function's final line makes rho contain the calculated density?

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

An axial stress function accepts force in newtons and area in square millimetres, and must return stress in megapascals:


Python
def axial_stress_mpa(force_n, area_mm2):
    # return expression goes here


Assume positive inputs and use


σ=FA,1 mm2=10−6 m2,1 MPa=106 Pa.\sigma=\frac{F}{A},\qquad 1\ \text{mm}^2=10^{-6}\ \text{m}^2,\qquad 1\ \text{MPa}=10^6\ \text{Pa}.


Which return statement satisfies the function's unit contract? A test call supplies 12000 N and 300 mm².

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 heater operates at constant electrical input power. The following Python 3 function returns useful heat energy in kilowatt-hours. Here, efficiency is the fraction of electrical energy converted to useful heat:


Python
def useful_heat_kwh(power_w, duration_min, efficiency=1.0):
    duration_h = duration_min / 60.0
    power_kw = power_w / 1000.0
    return power_kw * duration_h * efficiency

energy_kwh = useful_heat_kwh(
    duration_min=45.0,
    efficiency=0.80,
    power_w=1600.0
)


What value is stored in energy_kwh? Answer in kWh, to two decimal places.

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

Extra Practice