Nov 16, 2026 | 238 words | 2 min read
9.2.2. ICA: UDFs and Code Efficiency#
In this activity, you will …#
Revise Python code to improve efficiency and organization.
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")