\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch % NOTE: do NOT define \bar -- it is the built-in LaTeX accent used by \bar{x}, % \bar{y} (sample means). Redefining it made those render as the word "bar". \newcommand\barunit{\unit{bar}} \end{aligned}\end{align} \]

Nov 16, 2026 | 238 words | 2 min read

9.2.2. ICA: UDFs and Code Efficiency#

In this activity, you will …#

  1. Revise Python code to improve efficiency and organization.

  2. Practice writing user-defined functions (UDFs).

Learning Objectives#

  • PR01: Programming Standards

  • PR03: Calculations

  • PR04: Modular Programming

  • PR05: Code Structures

  • PR08: Debugging

Files Needed#

Download the Python file ENGR131_py2_ICA2.py and save it locally to your computer. Use the sample output section below to verify that your program outputs correct values.

Activity Instructions and Submission#

Part A: Code Analysis#

The Python script (“ENGR131_py2_ICA2.py”) estimates the mass of a few simple parts – rectangular blocks and solid cylinders – made from a few different materials (aluminum, steel, wood). It uses the idea that \(mass = density \times volume\), where block volume is \(L \times W \times H\) and cylinder volume is \(\pi r^2h\).

Carefully review the Python script, then answer the following question:

In what way(s) is the code inefficient? Identify and list the inefficiencies you find in the code. You can also include any other observations you have about the code that may be relevant to its efficiency or readability.

Part B: Code Revision and Debugging#

Revise the Python script to improve efficiency and organization. Afterwards, add clear comments explaining the changes you made and why they improved the code.

There are many potential solutions for solving this problem. A sample solution is provided below.

Note

The original code is intentionally written in an inefficient manner for instructional purposes. Your task is to identify and improve inefficiencies, not to critique the correctness of the calculations or the numerical results.

Solution#

View Sample Solution
import math

def get_density(material):
    """Return density (kg/m^3) for a given material using if/elif/else."""
    if material == "aluminum":
        density = 2700.0
    elif material == "steel":
        density = 7850.0
    elif material == "wood":
        density = 600.0
    else:
        density = 1000.0  # default for unrecognized materials
    return density

def block_volume(length, width, height):
    """Volume of a rectangular block (m^3)."""
    return length * width * height

def cylinder_volume(diameter, height):
    """Volume of a solid cylinder (m^3), given diameter and height."""
    radius = diameter / 2.0
    return math.pi * radius**2 * height

def get_volume(shape):
    """Ask the user for dimensions based on shape, and return the volume."""
    if shape == "block":
        length = float(input("  Enter length (m): "))
        width = float(input("  Enter width (m): "))
        height = float(input("  Enter height (m): "))
        volume = block_volume(length, width, height)
    elif shape == "cylinder":
        diameter = float(input("  Enter diameter (m): "))
        height = float(input("  Enter height (m): "))
        volume = cylinder_volume(diameter, height)
    else:
        print("  Shape not recognized -- volume set to 0.")
        volume = 0.0
    return volume

def classify_mass(mass):
    """Return a descriptive note based on mass (kg)."""
    if mass < 1:
        note = "Very light."
    elif mass < 10:
        note = "Moderate mass."
    else:
        note = "Heavy -- handle with care."
    return note

def compute_mass(part_name, material, volume):
    """Compute mass, print a summary line, and return the mass (kg)."""
    density = get_density(material)
    mass = density * volume
    note = classify_mass(mass)
    print(f"{part_name} mass: {mass:.3f} kg -- {note}")
    return mass


# ---- Part 1 ----
print("Part 1:")
material1 = input("  Enter material (aluminum/steel/wood): ").strip().lower()
shape1 = input("  Enter shape (block/cylinder): ").strip().lower()
V1 = get_volume(shape1)
m1 = compute_mass("Part 1", material1, V1)

# ---- Part 2 ----
print("\nPart 2:")
material2 = input("  Enter material (aluminum/steel/wood): ").strip().lower()
shape2 = input("  Enter shape (block/cylinder): ").strip().lower()
V2 = get_volume(shape2)
m2 = compute_mass("Part 2", material2, V2)

# ---- Part 3 ----
print("\nPart 3:")
material3 = input("  Enter material (aluminum/steel/wood): ").strip().lower()
shape3 = input("  Enter shape (block/cylinder): ").strip().lower()
V3 = get_volume(shape3)
m3 = compute_mass("Part 3", material3, V3)

# ---- Part 4 ----
print("\nPart 4:")
material4 = input("  Enter material (aluminum/steel/wood): ").strip().lower()
shape4 = input("  Enter shape (block/cylinder): ").strip().lower()
V4 = get_volume(shape4)
m4 = compute_mass("Part 4", material4, V4)

total_mass = m1 + m2 + m3 + m4
print(f"\nTotal mass: {total_mass:.3f} kg")