User-Defined Functions
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
Here, Δp is the pressure increase in pascals, Q is the flow rate in cubic metres per second, and η is the dimensionless pump efficiency expressed as a fraction. The resulting power is in watts because Pa⋅m3/s=W.
A suitable contract accepts nonnegative pressure and flow, with 0<η≤1. 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.
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_wThe 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:
power_w = pump_input_power(0.012, 150000.0, 0.75)
power_kw = power_w / 1000.0For these inputs,
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
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 kg, c=9.00×102 J/(kg⋅K), Ti=18.0 ∘C, and Tf=68.0 ∘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.
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.0The 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:
energy_kj = heating_energy_kj(2.40, 900.0, 18.0, 68.0)The temperature rise is
Substitute into the supplied energy relationship:
Convert to the required output unit:
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.
second_energy_kj = heating_energy_kj(3.60, 900.0, 18.0, 68.0)
total_energy_kj = energy_kj + second_energy_kjFor the second component,
Add the two returned energies:
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.
An axial stress function accepts force in newtons and area in square millimetres, and must return stress in megapascals:
def axial_stress_mpa(force_n, area_mm2):
# return expression goes hereAssume positive inputs and use
Which return statement satisfies the function's unit contract? A test call supplies 12000 N and 300 mm².
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:
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.