All articles →

100 Exercises / Python / 100 Python Exercises for Data Analysis

Reusable Python Functions for Production KPIs

Build reusable KPI functions, calculate dates and order quantities, and handle invalid input. Learn the assumptions behind statistical summaries.

100 Exercises Chapter 5 (No.041-No.050): Functions/Modules/Exception Handling

This is Chapter 5 (No.041–050) of 100 Python Exercises for Data Analysis. This chapter covers functions, modules, and exception handling using fictional harness production data.

About this material These notebooks were used in corporate training by Surikobo or its representative, Hiroshi Wayama, and were adapted for publication with permission. All data are fictional and do not represent actual company or factory results.

Example task

This is weekend work for Mr. T, the quality control team at the harness manufacturing factory.

Repeated work every weekend
  1. Manually calculate daily production volume, defect rate, and utilization rate for each of the five product lines.
  2. Copied and revised the defect rate calculation formula for 5 lines x 5 days, a total of 25 times.
  3. Calculate the estimated delivery date using Notepad by adding the lead time days to the parts order date.
  4. Processing stops due to "Unable to convert string to number" error when loading CSV

If you master Python’s functions, standard library, and exception handling, 25 copies into one function call, calendar calculation into one line of code, You can turn a pipeline that stops due to an error into a robust processing flow.

Common situations in the field

SceneTask
Repeat KPI calculationsManually calculate defect rate and operating rate by copying and pasting 5 lines
Calculating order quantityUse a calculator to calculate the required integer order quantity from minimum stock, lead time, and daily consumption amount
Confirm delivery datePerform calendar calculation of order date + lead time days using Notepad
CSV error handlingIf a string is mixed in a numeric field, the entire process will stop
Identifying the cause of the errorIt takes time to resolve the problem because you don’t know what happened in which row or column

In the situation where you write the same code for 5 lines, Sign of functionalization. In this chapter, you will learn the solution.

Common mistakes

Functions, modules, and exception handling have the following pitfalls.

  1. Forgot to write return Without return, the function return value will be None.
    Even if result = calc_revenue(...), result cannot be aggregated as None

  2. Function scope misunderstanding Variables defined within a function are not visible outside the function.
    As a general rule, avoid overusing the global variable and return the required value with return

  3. datetime module name conflict After import datetime you need to write datetime.date(...).
    It is easy to get confused when mixed with from datetime import datetime

  4. Abuse of except Exception Catching all errors in one hides unexpected bugs.
    Specify specific types such as ZeroDivisionError, ValueError, KeyError

Exercises in this chapter

No.TitleUsage in manufacturing industry
041Define a functionCreate a common function for defect rate calculation/Batch calculation for 5 lines
042Using argumentsKPI format function with default argument *args
043Using the return valueReturn defect rate, yield, and cycle time in a dictionary
044Create a function to calculate sales amountBatch calculation and visualization of 5 lines of non-defective product sales, defective loss, and amount after loss
045Create a function to calculate the average valueAverage, standard deviation, coefficient of variation of daily defect rate and weekly trend graph
046Importing the standard libraryImporting and basic confirmation of math, datetime, and statistics
047Using the math moduleRounding up the order quantity and calculating the 95% confidence interval for the defect rate
048Using the datetime moduleCalculating order date → scheduled delivery date, shift working hours, and number of days remaining at the end of the month
049Handling errors with try-exceptSafely handling type errors, missing columns, and value abnormalities when reading CSV
050Sorting out errors that tend to occur in data processingSystematically organizing five types of error patterns and countermeasures

Preparing the Python environment

Run cells in order from the top. Outputs are examples; the OS, versions, and file paths vary by environment. The setup cells import libraries and configure random data and plotting.

[IN: 1]
import platform
import sys

print(f"OS: {platform.platform()}")
print(f"Python: {sys.version.split()[0]}")
[OUT: 1]
OS: macOS-26.5.2-arm64-arm-64bit-Mach-O
Python: 3.14.4
Setup: Imports and display settings (expand)
[IN: 2]
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

matplotlib.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
%config InlineBackend.figure_format = 'svg'
np.random.seed(42)

print("Library loading completed")
print(f"  NumPy     : {np.__version__}")
print(f"  Matplotlib: {matplotlib.__version__}")
[OUT: 2]
Library loading completed
  NumPy     : 2.5.1
  Matplotlib: 3.11.0

Creating the sample data

Assumed scenario: Auto parts factory/harness production line quality control team Period: 3rd week of January 2024 (Monday to Friday, 5 days operation) Management target: 5 product lines (different product names, unit prices, and standard defect rates)

Setup: Generate the sample data (expand)
[IN: 3]
# Daily production data for 5 product lines x 5 days (2024-01-15~19)
lines = ["HA-01", "HA-02", "HB-01", "HB-02", "HC-01"]
line_names = ["harness A-thin", "Harness A-Medium", "harness B-thin", "Harness B-Medium", "harness C-thin"]
unit_prices = [1200, 1350, 980, 1100, 850]  # yen/piece

day_labels = ["Month (1/15)", "Tuesday (1/16)", "Wednesday (1/17)", "Thursday (1/18)", "Fri(1/19)"]

# Daily production count (seed=42)
base_prod = [450, 380, 520, 410, 480]
prod_data = np.array([[int(b + np.random.randint(-15, 16)) for _ in range(5)] for b in base_prod])

# Daily number of defects (standard defect rate 1.2-2.5% + random noise)
dr_base = [0.020, 0.015, 0.025, 0.018, 0.012]
defect_data = np.array(
    [[max(1, int(round(prod_data[i][j] * dr_base[i] + np.random.randn() * 0.8))) for j in range(5)] for i in range(5)]
)

# List of production counts
print(f"{'line':<8} {'Product name':<16} {'unit price':>8}  {'month':>4} {'fire':>4} {'water':>4} {'tree':>4} {'money':>4}  {'weekly total':>6}")
print("=" * 65)
for i in range(len(lines)):
    row_str = "  ".join(f"{int(prod_data[i][j]):>4}" for j in range(5))
    print(f"{lines[i]:<8} {line_names[i]:<16} {unit_prices[i]:>8,}  {row_str}  {int(prod_data[i].sum()):>6,}")
print()
print(f"{'line':<8} {'':16} {'Number of defects':>8}  {'month':>4} {'fire':>4} {'water':>4} {'tree':>4} {'money':>4}  {'weekly total':>6}")
print("=" * 65)
for i in range(len(lines)):
    row_str = "  ".join(f"{int(defect_data[i][j]):>4}" for j in range(5))
    print(f"{lines[i]:<8} {line_names[i]:<16} {'':>8}  {row_str}  {int(defect_data[i].sum()):>6}")
[OUT: 3]
line     Product name     unit price  month fire water tree money  weekly total
=================================================================
HA-01    harness A-thin      1,200   441   454   463   449   445   2,252
HA-02    Harness A-Medium    1,350   372   393   385   371   390   1,911
HB-01    harness B-thin        980   523   527   515   515   528   2,608
HB-02    Harness B-Medium    1,100   415   398   402   418   397   2,030
HC-01    harness C-thin        850   486   485   466   488   476   2,401

line                      Number of defects  month fire water tree money  weekly total
=================================================================
HA-01    harness A-thin                9     9     9     9     9      45
HA-02    Harness A-Medium              5     6     6     6     6      29
HB-01    harness B-thin               13    15    11    14    14      67
HB-02    Harness B-Medium              7     8     8     7     6      36
HC-01    harness C-thin                6     5     4     6     5      26

No.041: Define a function

Use in practice

When copying 5 lines of defect rate calculation formula defects / production * 100, When modifying the calculation logic, you need to modify all 5 locations. By organizing it into a function (def), you can manage your logic in one place.

Approach

Functions are a way to practice the DRY principle (Don’t Repeat Yourself). Manufacturing KPI calculations include defect rate, utilization rate, cycle time, etc. By defining it as a common function, it can be used even if the number of lines or aggregation period changes. Code changes are kept to a minimum.

Check with Python

[IN: 4]
# Define a function to calculate defect rate
def defect_rate(defects, production):
    """Returns defect rate (%)"""
    return defects / production * 100


# Single operation check
print("=== Check function operation ===")
print(f"defect_rate(9, 450)  = {defect_rate(9, 450):.2f}%")
print(f"defect_rate(6, 381)  = {defect_rate(6, 381):.2f}%")
print()

# 5 line batch calculation (effect of functionalization)
print(f"{'line':<8} {'weekly production':>8} {'Weekly defective':>8} {'Defect rate':>8}")
print("-" * 38)
for i in range(len(lines)):
    weekly_prod = int(prod_data[i].sum())
    weekly_defects = int(defect_data[i].sum())
    rate = defect_rate(weekly_defects, weekly_prod)
    print(f"{lines[i]:<8} {weekly_prod:>8,} {weekly_defects:>8} {rate:>7.2f}%")
[OUT: 4]
=== Check function operation ===
defect_rate(9, 450)  = 2.00%
defect_rate(6, 381)  = 1.57%

line     weekly production Weekly defective Defect rate
--------------------------------------
HA-01       2,252       45    2.00%
HA-02       1,911       29    1.52%
HB-01       2,608       67    2.57%
HB-02       2,030       36    1.77%
HC-01       2,401       26    1.08%

Interpreting the results

The calculation is defined once in defect_rate() and applied to all five lines. Add new lines to the input data and call the same function in the loop. This example assumes positive production; real inputs also need checks for zero production and valid defect counts.

The result is a percentage. If you change the scale, update the display labels and thresholds to use the same unit.


No.042: Use arguments

Use in practice

Arguments are values that can be changed depending on the situation, such as “production quantity, defective quantity, unit, accuracy”, etc. If you use the default argument, you can say “Usually this setting, change only when necessary.” You can create flexible functions. It can be used to generate reports for manufacturing KPIs.

Approach

There are four types of arguments: “positional arguments,” “keyword arguments,” “default arguments,” and “variable length arguments (*args).” In the manufacturing KPI function, if you set “unit, precision, label” as default arguments, While standard reports can be called in one line, special reports can also be supported.

Check with Python

[IN: 5]
# KPI formatting functions that use default arguments/keyword arguments
def format_kpi(label, value, unit="", precision=2, width=10):
    """Format and return KPI labels and values"""
    formatted = f"{value:.{precision}f}"
    return f"{label}: {formatted:>{width}}{unit}"


# Checking the operation of default arguments
print(format_kpi("Defect rate", 2.02, unit="%"))  # default precision
print(format_kpi("weekly production", 2255, unit="units", precision=0))
print(format_kpi("Operating hours", 7.5, unit="h"))
print()


# Variable length argument with *args: Identify the worst line from the defect rate of multiple lines
def worst_line_idx(*defect_rates):
    """Returns the index and value of the line with the highest defect rate"""
    max_rate = max(defect_rates)
    idx = list(defect_rates).index(max_rate)
    return idx, max_rate


weekly_rates = [defect_rate(int(defect_data[i].sum()), int(prod_data[i].sum())) for i in range(len(lines))]
worst_idx, worst_rate = worst_line_idx(*weekly_rates)
print(f"Highest defect rate line: {lines[worst_idx]}({worst_rate:.2f}%)")
print()


# **kwargs for future expansion
def kpi_header(**metadata):
    """Generate report header"""
    parts = [f"{k}={v}" for k, v in metadata.items()]
    return "[ " + " / ".join(parts) + " ]"


header = kpi_header(factory="Harness manufacturing building", week="2024-W03", shift="Daytime shift")
print(header)
[OUT: 5]
Defect rate:       2.02%
weekly production:       2255units
Operating hours:       7.50h

Highest defect rate line: HB-01(2.57%)

[ factory=Harness manufacturing building / week=2024-W03 / shift=Daytime shift ]

Interpreting the results

format_kpi("Defect rate", 2.02, unit="%") uses the default precision=2. The *weekly_rates expression passes the five rates as separate arguments to worst_line_idx(). **kwargs accepts named metadata fields when their number can vary.


No.043: Use return value

Use in practice

Returning related KPIs together avoids repeating calculations in the caller. This example returns a dictionary containing total production, defect rate, cycle time, and other values.

Approach

If you return the return value as a tuple, you can use “unpacking assignment (a, b, c = func())”, Storing it in a variable can be done in one line. Select whether to return multiple related indicators as a tuple or as a dictionary ({}). If you return it as a dictionary, you can use result["defect_rate"] when “only a part of the result is used”. Dictionaries are recommended when there are many output items because they can be retrieved by key.

Check with Python

[IN: 6]
# A function that returns weekly key KPIs in a dictionary
def production_kpi(production_list, defect_list, unit_price, operated_hours_total):
    """Calculate weekly key KPIs and return them in a dictionary

    Parameters
    ----------
    production_list : list[int] - Daily production count
    defect_list : list[int] - Daily number of defects
    unit_price : int - Unit price (yen/piece)
    operated_hours_total : float - Weekly operating hours (hours)

    Returns
    -------
    dict: total_prod, total_defects, good_units, defect_rate,
          yield_rate, cycle_time_s, revenue"""
    total_prod = sum(production_list)
    total_defects = sum(defect_list)
    good_units = total_prod - total_defects
    dr_pct = total_defects / total_prod * 100
    yield_pct = good_units / total_prod * 100
    cycle_sec = operated_hours_total * 3600 / total_prod
    revenue = good_units * unit_price
    return {
        "total_prod": total_prod,
        "total_defects": total_defects,
        "good_units": good_units,
        "defect_rate": dr_pct,
        "yield_rate": yield_pct,
        "cycle_time_s": cycle_sec,
        "revenue": revenue,
    }


# Calculate weekly KPIs for HA-01
operated_week = 7.5 * 5  # 7.5h x 5 days
kpi_ha01 = production_kpi(
    production_list=[int(x) for x in prod_data[0]],
    defect_list=[int(x) for x in defect_data[0]],
    unit_price=unit_prices[0],
    operated_hours_total=operated_week,
)

print("=== HA-01 Weekly KPI ===")
print(f"  Total production count     : {kpi_ha01['total_prod']:,} units")
print(f"  Total number of defects     : {kpi_ha01['total_defects']} units")
print(f"  Number of good products       : {kpi_ha01['good_units']:,} units")
print(f"  Defect rate       : {kpi_ha01['defect_rate']:.2f}%")
print(f"  Good product rate (yield): {kpi_ha01['yield_rate']:.2f}%")
print(f"  cycle time: {kpi_ha01['cycle_time_s']:.1f} seconds/units")
print(f"  Good product sales     : {kpi_ha01['revenue']:,.0f} JPY")
[OUT: 6]
=== HA-01 Weekly KPI ===
  Total production count     : 2,252 units
  Total number of defects     : 45 units
  Number of good products       : 2,207 units
  Defect rate       : 2.00%
  Good product rate (yield): 98.00%
  cycle time: 59.9 seconds/units
  Good product sales     : 2,648,400 JPY

Interpreting the results

The return value is a dictionary, so you can select a metric by name, such as kpi_ha01["defect_rate"]. HA-01’s average cycle time is 59.9 seconds per unit, calculated by converting 37.5 operating hours to seconds and dividing by 2,252 units. Pass another line’s data to apply the same formulas.


No.044: Create a function to calculate sales amount

Use in practice

The formula “Sales of non-defective products - Losses from defects = Net profit” is common to all lines. The disposal cost rate (penalty_rate) for defective products varies depending on the line, but By setting it as a default argument, normal lines can be processed with the same expression.

Approach

This exercise uses good units times unit price as a sales-equivalent amount, and defective units times unit price times (1 + penalty_rate) as an assumed loss. The value penalty_rate=0.30 is a teaching assumption, not an industry standard. The displayed amount after loss is not profit after production and operating costs. Define business calculations using actual shipments and costs.

Check with Python

[IN: 7]
# Functions to calculate sales of non-defective products, loss of non-conforming products, and amount after loss
def calc_revenue(production, defects, unit_price, penalty_rate=0.30):
    """Calculate weekly revenue metrics

    Parameters
    ----------
    production: int - number of production
    defects : int - number of defects
    unit_price : int - Unit price (yen/piece)
    penalty_rate : float - Defective product scrapping cost rate (default 0.30)

    Returns
    -------
    dict: good_units, revenue, loss, net_revenue, loss_ratio_pct"""
    good_units = production - defects
    revenue = good_units * unit_price
    loss = defects * unit_price * (1 + penalty_rate)
    net_revenue = revenue - loss
    loss_ratio = loss / (revenue + loss) * 100
    return {
        "good_units": good_units,
        "revenue": revenue,
        "loss": loss,
        "net_revenue": net_revenue,
        "loss_ratio_pct": loss_ratio,
    }


# All 5 lines weekly profit calculation
results_044 = []
print(f"{'line':<8} {'Good product sales':>12} {'defect loss':>10} {'amount after loss':>12} {'loss rate':>8}")
print("=" * 56)
for i in range(len(lines)):
    prod_w = int(prod_data[i].sum())
    defect_w = int(defect_data[i].sum())
    r = calc_revenue(prod_w, defect_w, unit_prices[i])
    results_044.append(r)
    print(
        f"{lines[i]:<8} {r['revenue']:>12,.0f} {r['loss']:>10,.0f} "
        f"{r['net_revenue']:>12,.0f} {r['loss_ratio_pct']:>7.1f}%"
    )

total_rev = sum(r["revenue"] for r in results_044)
total_los = sum(r["loss"] for r in results_044)
total_net = sum(r["net_revenue"] for r in results_044)
print("=" * 56)
print(f"{'Total':<8} {total_rev:>12,.0f} {total_los:>10,.0f} {total_net:>12,.0f}")
[OUT: 7]
line     Good product sales defect loss amount after loss loss rate
========================================================
HA-01       2,648,400     70,200    2,578,200     2.6%
HA-02       2,540,700     50,895    2,489,805     2.0%
HB-01       2,490,180     85,358    2,404,822     3.3%
HB-02       2,193,400     51,480    2,141,920     2.3%
HC-01       2,018,750     28,730    1,990,020     1.4%
========================================================
Total      11,891,430    286,663   11,604,767
[IN: 8]
# Bar graph of non-defective product sales, defective losses, and amounts after assumed losses by line
fig, ax = plt.subplots(figsize=(10, 5))

revenues = [r["revenue"] for r in results_044]
losses = [r["loss"] for r in results_044]
net_revenues = [r["net_revenue"] for r in results_044]

x = np.arange(len(lines))
width = 0.28

ax.bar(x - width, revenues, width, label="Good product sales", color="#4C72B0", alpha=0.88)
ax.bar(x, losses, width, label="defect loss", color="#DD8452", alpha=0.88)
ax.bar(x + width, net_revenues, width, label="amount after loss", color="#55A868", alpha=0.88)

ax.set_title("Weekly amounts and assumed losses by line\n(January 15–19, 2024)", fontsize=13, pad=10)
ax.set_xlabel("product line", fontsize=11)
ax.set_ylabel("Amount (million yen)", fontsize=11)
ax.set_xticks(x)
ax.set_xticklabels(lines)
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda v, _: f"{v/1_000_000:.1f}"))
ax.legend(fontsize=10)
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 8]

Weekly amounts and assumed losses by line / (January 15–19, 2024)

Interpreting the results

calc_revenue() applies the same formulas to all five lines, comparing good units times unit price, assumed defect losses, and the amount remaining after those losses. These are not actual profits. Changing penalty_rate=0.30 to 0.50 shows how the assumed disposal cost affects the result. Varying an input to examine the change in the result is called sensitivity analysis.


No.045: Create a function to calculate the average value

Use in practice

The mean, maximum, minimum, and standard deviation summarize the level and variation observed over five days. The coefficient of variation (CV) is the standard deviation divided by the mean and describes relative variation. It can become large when the mean is close to zero, so do not judge quality from CV alone.

Approach

Calculate the mean, variance, and standard deviation with sum() and arithmetic. The variance uses the number of observations, n, as its denominator because this example describes the five observed days. Assess statistical process stability separately using time-series data or control charts.

An empty list raises an error. If the mean is zero, CV is undefined and the function returns nan.

Check with Python

[IN: 9]
# Generic function to calculate descriptive statistics (without NumPy)
def calc_stats(data):
    """Calculate the average, maximum, minimum, standard deviation, and coefficient of variation

    Parameters
    ----------
    data : list[float] - numeric list

    Returns
    -------
    dict: mean, max_v, min_v, std, cv_pct"""
    if not data:
        raise ValueError("data must contain at least one value")

    n = len(data)
    mean_v = sum(data) / n
    var = sum((x - mean_v) ** 2 for x in data) / n  # Variance of the observed data (denominator n)
    std_v = var**0.5
    cv_pct = std_v / mean_v * 100 if mean_v != 0 else float("nan")  # Coefficient of variation (%)
    return {
        "mean": mean_v,
        "max_v": max(data),
        "min_v": min(data),
        "std": std_v,
        "cv_pct": cv_pct,
    }


# Calculate the daily defect rate for each line and store it in a list
daily_defect_rates_045 = [[defect_data[i][j] / prod_data[i][j] * 100 for j in range(5)] for i in range(len(lines))]

# Statistics summary table
print(f"{'line':<8} {'Average defect rate':>10} {'maximum':>8} {'minimum':>8} {'standard deviation':>10} {'coefficient of variation':>10}")
print("=" * 60)
for i, line in enumerate(lines):
    s = calc_stats(daily_defect_rates_045[i])
    print(
        f"{line:<8} {s['mean']:>9.2f}% {s['max_v']:>7.2f}% {s['min_v']:>7.2f}%"
        f" {s['std']:>9.3f}% {s['cv_pct']:>9.1f}%"
    )

# Weekly defect rate for all lines total
total_prod_all = int(prod_data.sum())
total_defects_all = int(defect_data.sum())
overall_dr = total_defects_all / total_prod_all * 100
print("=" * 60)
print(f"{'Overall':<8} {overall_dr:>9.2f}%  (total production {total_prod_all:,}units / Total defective {total_defects_all}units)")
[OUT: 9]
line     Average defect rate  maximum  minimum standard deviation coefficient of variation
============================================================
HA-01         2.00%    2.04%    1.94%     0.034%       1.7%
HA-02         1.52%    1.62%    1.34%     0.092%       6.1%
HB-01         2.57%    2.85%    2.14%     0.245%       9.5%
HB-02         1.77%    2.01%    1.51%     0.194%      11.0%
HC-01         1.08%    1.23%    0.86%     0.140%      13.0%
============================================================
Overall       1.81%  (total production 11,202units / Total defective 203units)
[IN: 10]
# Daily defect rate trend graph (all lines)
fig, ax = plt.subplots(figsize=(10, 5))
colors_045 = ["#4C72B0", "#DD8452", "#55A868", "#C44E52", "#8172B2"]

for i, line in enumerate(lines):
    ax.plot(
        day_labels, daily_defect_rates_045[i], marker="o", label=line, color=colors_045[i], linewidth=2, markersize=6
    )

# Warning line (2.0%)
ax.axhline(2.0, color="red", linewidth=1.5, linestyle="--", alpha=0.7, label="Warning line (2.0%)")

ax.set_title("Daily defect rate trends by product line (3rd week of January 2024)", fontsize=13, pad=10)
ax.set_xlabel("date", fontsize=11)
ax.set_ylabel("Defect rate (%)", fontsize=11)
ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=9)
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 10]

Daily defect rate trends by product line (3rd week of January 2024)

Interpreting the results

calc_stats() returns the square root of the variance, var ** 0.5, as the standard deviation. HB-01 has the highest mean defect rate at 2.57%, while HC-01 has the highest CV at 13.0%. A high CV is different from a high defect rate. Compare daily values with the 2.0% threshold in the chart.


No.046: Import standard library

Use in practice

Python has a rich standard library that can be used without additional installation with pip. Frequently used in manufacturing data processing are math (mathematics), datetime (date and time), statistics (statistics), csv (CSV read/write) and os (file path).

Approach

Load the standard library with import library name. statistics module can calculate mean, variance, and median without numpy. However, numpy is required for fast processing of large amounts of data. Use standard libraries and external libraries depending on the situation.

Check with Python

[IN: 11]
# Importing standard libraries often used in manufacturing data processing
import math
import datetime
import statistics
import os
import sys

print("=== Standard library confirmation ===")
for name, mod in [("math", math), ("datetime", datetime), ("statistics", statistics), ("os", os), ("sys", sys)]:
    print(f"  {name:<12}: {mod.__name__}")
print()

# Aggregating daily defect rates using the statistics module
all_daily_rates = [defect_data[i][j] / prod_data[i][j] * 100 for i in range(len(lines)) for j in range(5)]

print(f"statistics.mean()    : {statistics.mean(all_daily_rates):.3f}%")
print(f"statistics.median()  : {statistics.median(all_daily_rates):.3f}%")
print(f"statistics.stdev()   : {statistics.stdev(all_daily_rates):.3f}%   # sample standard deviation")
print(f"statistics.variance(): {statistics.variance(all_daily_rates):.4f}")
print()
print(f"  [Reference] No.045 of calc_stats() comparison with")
s = calc_stats(all_daily_rates)
print(f"  calc_stats mean: {s['mean']:.3f}%  / std: {s['std']:.3f}%  (population standard deviation)")
[OUT: 11]
=== Standard library confirmation ===
  math        : math
  datetime    : datetime
  statistics  : statistics
  os          : os
  sys         : sys

statistics.mean()    : 1.788%
statistics.median()  : 1.687%
statistics.stdev()   : 0.531%   # sample standard deviation
statistics.variance(): 0.2819

  [Reference] No.045 of calc_stats() comparison with
  calc_stats mean: 1.788%  / std: 0.520%  (population standard deviation)

Interpreting the results

statistics.stdev() returns the square root of the sample variance, whose denominator is n−1n-1. In No.045, calc_stats() uses nn to describe the five observed days. NumPy’s np.std() also defaults to ddof=0, with denominator nn.

Describing the observed period and estimating variation in a broader process are different tasks. Having every record for this week does not reveal the standard deviation of future production. Also distinguish an unbiased variance estimate from an unbiased standard deviation estimate.


No.047: Use math module

Use in practice

A typical example of how to use the math module at a manufacturing site is ① Round up calculation (math.ceil) of order quantity ② Confidence interval calculation (math.sqrt) in statistical quality control. math.ceil is required for the constraint that “order quantities must be whole numbers”.

Approach

math.ceil(x) returns the smallest integer greater than or equal to x. Use it when ordering whole units without falling below the calculated requirement.

The interval calculation illustrates a normal approximation (the Wald interval) under a binomial model with independent trials and a common defect probability:

p^±1.96p^(1−p^)n\hat p \pm 1.96\sqrt{\frac{\hat p(1-\hat p)}{n}}

Here nn is the number inspected and p^\hat p is the defective proportion, between 0 and 1. This approximation needs sufficiently many defective and nondefective observations; it is unsuitable for small counts or proportions near 0 or 1. The example data use different baseline rates for different lines, so the pooled interval should not be applied directly to individual lines.

Check with Python

[IN: 12]
# The interval below assumes independent trials with a common defect probability.
import math

# Calculation of order quantity rounding up
min_stock_47 = 200  # Minimum stock quantity (pieces)
current_stock_47 = 143  # Current stock quantity (pieces)
daily_usage_47 = 18.7  # Average daily usage (pcs/day)
lead_days_47 = 5  # Order lead time (days)

# Consumption amount during order period + minimum stock maintenance amount
order_exact = (min_stock_47 - current_stock_47) + daily_usage_47 * lead_days_47
order_qty = math.ceil(order_exact)  # Round up to whole number

print(f"=== Order quantity calculation ===")
print(f"  Shortage in stock       : {min_stock_47 - current_stock_47} units")
print(f"  Lead time consumption  : {daily_usage_47} × {lead_days_47} = {daily_usage_47 * lead_days_47:.1f} units")
print(f"  Theoretical order quantity (There are fractions): {order_exact:.2f} units")
print(f"  Actual number of orders (Kirigami): {order_qty} units  ← math.ceil() Applicable")
print()

# 95% confidence interval for weekly defect rate
total_prod_47 = int(prod_data.sum())
total_defects_47 = int(defect_data.sum())
p_hat = total_defects_47 / total_prod_47
hw = 1.96 * math.sqrt(p_hat * (1 - p_hat) / total_prod_47)

print(f"=== Defect rate 95% confidence interval ===")
print(f"  Total production count  : {total_prod_47:,} units")
print(f"  Total number of defects  : {total_defects_47} units")
print(f"  Defect rate estimate: {p_hat*100:.4f}%")
print(f"  95% CI      : [{(p_hat-hw)*100:.4f}%, {(p_hat+hw)*100:.4f}%]")
print()

# math function reference
print("=== math main functions ===")
print(f"  math.ceil(3.2)    : {math.ceil(3.2)}")
print(f"  math.floor(3.8)   : {math.floor(3.8)}")
print(f"  math.sqrt(2)      : {math.sqrt(2):.6f}")
print(f"  math.log(math.e)  : {math.log(math.e):.6f}  # natural logarithm")
print(f"  math.log10(1000)  : {math.log10(1000):.6f}  # common logarithm")
print(f"  math.pi           : {math.pi:.6f}")
[OUT: 12]
=== Order quantity calculation ===
  Shortage in stock       : 57 units
  Lead time consumption  : 18.7 × 5 = 93.5 units
  Theoretical order quantity (There are fractions): 150.50 units
  Actual number of orders (Kirigami): 151 units  ← math.ceil() Applicable

=== Defect rate 95% confidence interval ===
  Total production count  : 11,202 units
  Total number of defects  : 203 units
  Defect rate estimate: 1.8122%
  95% CI      : [1.5652%, 2.0592%]

=== math main functions ===
  math.ceil(3.2)    : 4
  math.floor(3.8)   : 3
  math.sqrt(2)      : 1.414214
  math.log(math.e)  : 1.000000  # natural logarithm
  math.log10(1000)  : 3.000000  # common logarithm
  math.pi           : 3.141593

Interpreting the results

Rounding the required 150.5 units upward with math.ceil() gives 151 units.

Under the exercise’s assumptions, the approximate 95% confidence interval is 1.5652%–2.0592%. The 95% describes the procedure: if sampling and interval calculation were repeated under the same conditions, about 95% of the resulting intervals would contain the true proportion. It does not assign a 95% probability to the true value being in this particular interval. Confidence intervals and control-chart limits also serve different purposes.


No.048: Use datetime module

Use in practice

The main uses of datetime at manufacturing sites are ①** Calculation of scheduled delivery date** (order date + number of lead time days) ②** Calculation of shift working time** (end time − start time − break time) ③Check the number of days remaining until the end of the month/period (calculation of remaining amount of production plan) There are three. These can be automated by manual calculation or by visually checking the calendar.

Approach

Focusing on two classes: datetime.date and datetime.timedelta You can add and subtract dates. timedelta(days=5) is a “time difference object” for calculating “5 days later”. By converting to a format string with strftime(), You can automatically generate date displays for reports and notification emails.

Check with Python

[IN: 13]
import datetime

# Calculate the estimated delivery date from the order date
order_date_48 = datetime.date(2024, 1, 15)  # Ordered on Monday
lead_days_48 = 5
delivery_date_48 = order_date_48 + datetime.timedelta(days=lead_days_48)

print("=== Order/Delivery Schedule ===")
print(f"  Order date      : {order_date_48.strftime('%Y-%m-%d (%a)')}")
print(f"  lead time: {lead_days_48} days")
print(f"  Expected delivery date  : {delivery_date_48.strftime('%Y-%m-%d (%a)')}")
print()

# Shift working time calculation
shift_start_48 = datetime.datetime(2024, 1, 15, 8, 0, 0)
shift_end_48 = datetime.datetime(2024, 1, 15, 17, 0, 0)
break_time_48 = datetime.timedelta(minutes=60)
worked_td = shift_end_48 - shift_start_48 - break_time_48
worked_hours_48 = worked_td.total_seconds() / 3600

print("=== Shift Working Time ===")
print(f"  Start of shift: {shift_start_48.strftime('%H:%M')}")
print(f"  End of shift: {shift_end_48.strftime('%H:%M')}")
print(f"  Break time  : 60 minutes")
print(f"  Actual operating time: {worked_hours_48:.1f} hours")
print()

# Number of days remaining until the end of the month/weekend
today_48 = datetime.date(2024, 1, 19)  # Friday of the 3rd week
month_end = datetime.date(2024, 1, 31)
remaining_days = (month_end - today_48).days

print("=== Number of days remaining until the end of the month ===")
print(f"  Today  : {today_48}")
print(f"  end of month  : {month_end}")
print(f"  Remaining days: {remaining_days} days")
print()

# Automatically generates 5-day production schedule dates
print("=== Weekly production schedule ===")
weekday_map = {0: "Month", 1: "fire", 2: "water", 3: "tree", 4: "money", 5: "soil", 6: "days"}
for d in range(5):
    dt = order_date_48 + datetime.timedelta(days=d)
    prod_total = int(prod_data[:, d].sum())
    print(f"  {dt.strftime('%m/%d')} ({weekday_map[dt.weekday()]})  Total production of all lines: {prod_total:,} units")
[OUT: 13]
=== Order/Delivery Schedule ===
  Order date      : 2024-01-15 (Mon)
  lead time: 5 days
  Expected delivery date  : 2024-01-20 (Sat)

=== Shift Working Time ===
  Start of shift: 08:00
  End of shift: 17:00
  Break time  : 60 minutes
  Actual operating time: 8.0 hours

=== Number of days remaining until the end of the month ===
  Today  : 2024-01-19
  end of month  : 2024-01-31
  Remaining days: 12 days

=== Weekly production schedule ===
  01/15 (Month)  Total production of all lines: 2,237 units
  01/16 (fire)  Total production of all lines: 2,257 units
  01/17 (water)  Total production of all lines: 2,231 units
  01/18 (tree)  Total production of all lines: 2,241 units
  01/19 (money)  Total production of all lines: 2,236 units

Interpreting the results

Adding timedelta(days=5) to January 15, 2024 gives Saturday, January 20, five calendar days later. It does not calculate five working days by excluding weekends and holidays. Use the company’s operating calendar for business-day calculations.

For shift duration, subtract the start time and break from the end time, then convert the result to hours with total_seconds() / 3600.


No.049: Handle errors with try-except

Use in practice

External data can contain text in numeric fields, missing columns, or negative counts. This example validates each row, records errors, and continues processing valid rows. Decide whether to continue or stop based on the impact on the result.

Approach

If an error occurs in the try block, processing moves to the corresponding except block. By writing multiple except, you can branch processing depending on the type of error. finally block is always executed regardless of success or failure, so It is used for file closing processing (details will be covered in Chapter 6).

Check with Python

[IN: 14]
import math

# Function to safely parse a single line of CSV
def safe_parse_row(row, row_num=0):
    """Parse one CSV line (list format) and return result dictionary or error dictionary

    Expected error
    ----------
    IndexError: Insufficient number of columns
    ValueError: Type conversion failure/value error"""
    try:
        product_code = row[0]  # Part number (string)
        production = int(row[1])  # Production count → int conversion
        defects = int(row[2])  # Number of defects → int conversion
        unit_price = float(row[3])  # Unit price → float conversion

        # Validation of business rules
        if production <= 0:
            raise ValueError(f"Production quantity must be a positive integer: {production}")
        if defects < 0:
            raise ValueError("Defect count must be nonnegative")
        if not math.isfinite(unit_price) or unit_price < 0:
            raise ValueError("Unit price must be finite and nonnegative")
        if defects > production:
            raise ValueError(f"Number of defects({defects})is the number of production({production})exceeds")

        dr = defects / production * 100
        return {
            "code": product_code,
            "production": production,
            "defects": defects,
            "unit_price": unit_price,
            "defect_rate": dr,
        }

    except IndexError:
        return {"error": f"rows{row_num}: Insufficient number of columns ({len(row)} column)", "row": row}
    except ValueError as e:
        return {"error": f"rows{row_num}: Value error ({e})", "row": row}


# Test data (normal/abnormal mixture)
test_rows_049 = [
    ["HA-01", "450", "9", "1200"],  # ✅ Normal
    ["HA-02", "381", "6", "1350"],  # ✅ Normal
    ["HB-01", "525", "abc", "980"],  # ❌ ValueError (number of defects is a string)
    ["HB-02", "415"],  # ❌ IndexError (missing columns)
    ["HC-01", "485", "520", "850"],  # ❌ ValueError (Number of defects > Number of production)
    ["HC-01", "0", "0", "850"],  # ❌ ValueError (production quantity = 0)
]

print("=== CSV row analysis result ===")
ok_rows, ng_rows = [], []
for i, row in enumerate(test_rows_049, start=1):
    result = safe_parse_row(row, row_num=i)
    if "error" in result:
        ng_rows.append(result)
        print(f"  ❌ {result['error']}")
    else:
        ok_rows.append(result)
        print(f"  ✅ rows{i}: {result['code']}  production{result['production']:>4}units  " f"Defect rate{result['defect_rate']:.2f}%")

print()
print(f"Normal processing: {len(ok_rows)} rows / skip: {len(ng_rows)} rows")
[OUT: 14]
=== CSV row analysis result ===
  ✅ rows1: HA-01  production 450units  Defect rate2.00%
  ✅ rows2: HA-02  production 381units  Defect rate1.57%
  ❌ rows3: Value error (invalid literal for int() with base 10: 'abc')
  ❌ rows4: Insufficient number of columns (2 column)
  ❌ rows5: Value error (Number of defects(520)is the number of production(485)exceeds)
  ❌ rows6: Value error (Production quantity must be a positive integer: 0)

Normal processing: 2 rows / skip: 4 rows

Interpreting the results

The six example rows produce two valid rows and four errors. Missing columns are handled as IndexError; conversion and range problems are handled as ValueError. Keep the original row and the reason. Also reject negative defect counts and negative or nonfinite prices. A summary of valid rows is not a summary of all rows, so report how many records were excluded.


No.050: Sort out errors that tend to occur in data processing

Use in practice

There are certain patterns of errors that occur in manufacturing data processing.
5 types of errors (ZeroDivisionError/KeyError/TypeError/ValueError/IndexError) By systematically understanding them and preparing appropriate solutions as codes, This can significantly reduce troubleshooting time in the production environment.

Approach

Error handling is the basis of “defensive programming”. Anticipate in advance what will be included in this data, try-except can be combined with pre-validation (confirmation with if statement). Design principles for robust data pipelines.

Check with Python

[IN: 15]
# 5 types of errors that frequently occur in data processing and how to deal with them

error_catalog = [
    {
        "type": "ZeroDivisionError",
        "scene": "Defect rate calculation when production quantity is 0",
        "trigger": "defects / production * 100  (production=0)",
        "fix": "Check production > 0 or try-except",
    },
    {
        "type": "KeyError",
        "scene": "Accessing keys not present in dictionary",
        "trigger": "part_info['supplier'] (key not registered)",
        "fix": "part_info.get('supplier', 'unknown')",
    },
    {
        "type": "TypeError",
        "scene": "String and number operations",
        "trigger": "'326' + 15  (str + int)",
        "fix": "Type conversion with int('326') + 15",
    },
    {
        "type": "ValueError",
        "scene": "Convert unconvertable strings to numbers",
        "trigger": "int('12a') (non-numeric string)",
        "fix": "Skip with try-except ValueError",
    },
    {
        "type": "IndexError",
        "scene": "List out-of-bounds access",
        "trigger": "row[5] (CSV with only 5 columns)",
        "fix": "Check len(row) > 5 or try-except",
    },
]

print(f"{'Error type':<22} {'Occurrence scene':<28} {'How to deal with it'}")
print("=" * 80)
for e in error_catalog:
    print(f"{e['type']:<22} {e['scene']:<28} {e['fix']}")
print()

# try-except demonstration of each error
print("=== try-except demonstration ===")

# ZeroDivisionError
try:
    rate_050 = 3 / 0
except ZeroDivisionError:
    rate_050 = None
print(f"ZeroDivisionError → rate = {rate_050}  (None Set and continue processing)")

# KeyError (avoided with get())
part_info_050 = {"code": "HA-01", "production": 450}
supplier_050 = part_info_050.get("supplier", "Not registered")
print(f"KeyError avoidance     → supplier = '{supplier_050}'  (get() default value of)")

# TypeError
try:
    result_050 = "326" + 15
except TypeError:
    result_050 = int("326") + 15
print(f"TypeError avoidance    → result = {result_050}  (int() Convert and recalculate with)")

# ValueError
try:
    v_050 = int("12a")
except ValueError as e:
    v_050 = None
    e_msg_050 = str(e)
print(f"ValueError avoidance   → v = {v_050}  ('{e_msg_050}' → skip)")

# IndexError
row_050 = ["HC-01", "480"]
try:
    defects_050 = int(row_050[2])
except IndexError:
    defects_050 = 0
print(f"IndexError avoidance   → defects = {defects_050}  (Not enough rows → default0set)")
[OUT: 15]
Error type             Occurrence scene             How to deal with it
================================================================================
ZeroDivisionError      Defect rate calculation when production quantity is 0 Check production > 0 or try-except
KeyError               Accessing keys not present in dictionary part_info.get('supplier', 'unknown')
TypeError              String and number operations Type conversion with int('326') + 15
ValueError             Convert unconvertable strings to numbers Skip with try-except ValueError
IndexError             List out-of-bounds access    Check len(row) > 5 or try-except

=== try-except demonstration ===
ZeroDivisionError → rate = None  (None Set and continue processing)
KeyError avoidance     → supplier = 'Not registered'  (get() default value of)
TypeError avoidance    → result = 341  (int() Convert and recalculate with)
ValueError avoidance   → v = None  ('invalid literal for int() with base 10: '12a'' → skip)
IndexError avoidance   → defects = 0  (Not enough rows → default0set)

Interpreting the results

We have organized a list of 5 types of errors and how to deal with them. In an actual data pipeline, you can choose to return an error,'' use default value,” or “skip and log.” Choose a policy that fits the situation.

Response policyWhen to use
Set None and continue processingWhen it can be treated as missing in aggregation processing
Default value (get(), etc.)If the key or column is an optional item
Skip with except + LogExcluding abnormal rows and counting only normal rows
Raise an exception with raiseIn case of serious abnormality that should notify the caller of the error

The design of “which errors allow processing to continue and which require stopping or notification” It determines the quality of your manufacturing data pipeline.


Applying the exercises at work

The “functions, modules, and exception handling” learned in No.041-050 are These are the basic skills that determine the design quality of a manufacturing KPI system.

1. Functionalization = “Reduction of maintenance costs”

A code with 5 lines of the same calculations would need to be modified in 5 places every time the specifications change. By consolidating into one function like calc_revenue(), Changes in specifications can be reflected in the entire line with a single modification. At manufacturing sites, the number of lines increases/the definition of KPIs changes, so Functionalization is a design that increases resistance to change.

2. Standard library = “No installation required productivity tools”

Rounding up the order quantity using math.ceil Delivery date calculation using datetime.timedelta is Ready to use without any additional libraries. Even in a manufacturing IT environment where a request to install a tool is not successful. Many tasks can be automated using the standard library.

3. Exception handling = “Data pipeline quality assurance”

Handle known error types and record the input row and reason. If processing continues, report excluded records and unprocessed data alongside the result. Missing required files or errors affecting the whole summary may warrant stopping for review.

Applying the code to your data

This section describes the steps to implement what you have learned in this chapter into your manufacturing site data system.

Step 1: Creating a KPI function library (about 1 day)

Use the functions created in this chapter such as defect_rate(), calc_revenue(), calc_stats(), etc. Combine them into one file as kpi_functions.py. Can be reused with from kpi_functions import calc_revenue from other notebook scripts.

Step 2: Schedule automation using datetime (about half a day)

Implement the calculation of order date, scheduled delivery date, and number of days remaining at the end of the month using the datetime function, Automate daily routine tasks (order alerts, schedule confirmation).

Step 3: Build a secure CSV loading pipeline (about 1 day)

Use safe_parse_row() to “summarize only normal rows while skipping abnormal rows” Build the loading function. Chapter 6 (File Operations and CSV) completes this pipeline by loading an actual CSV file.

Step 4: Output error log (about half a day)

except The abnormal row detected in the block Add a mechanism to write to a file such as error_log.csv. This allows you to know which rows were skipped, what errors occurred, and why. The data manager can check it later.

Summary

We will summarize what we learned in this chapter (No.041-050).

No.SkillsUtilization at manufacturing sites
041Define a functionCommon function for defect rate calculation/5-line batch calculation
042Use argumentsKPI format with default arguments, identify worst line with *args
043Use return valuesReturn multiple KPIs (defect rate, non-defect rate, cycle time, sales) using a dictionary
044Create a function to calculate sales amountBatch calculation of 5-line weekly profits and bar graph visualization
045Create a function to calculate the average valueDescriptive statistics, coefficient of variation, and weekly trend graph of daily defect rate
046Importing the standard libraryImporting and using math, datetime, and statistics
047Using the math moduleRounding up the order quantity and calculating the 95% confidence interval for the defect rate
048Using the datetime moduleCalculate order date → scheduled delivery date, shift operating hours, and remaining days
049Responding to errors with try-exceptAggregating only normal rows while processing CSV abnormal data
050Sorting out errors that tend to occur in data processingSystematically organizing five types of error patterns and countermeasures

Chapter 6 (No.051-060) uses file operations and the CSV module to Combining the functions and exception handling in this chapter from the actual file Build a full-fledged data pipeline.

Training and analysis support


Surikobo provides Python training and data analysis support for manufacturing industry and DX promotion staff.

Do you have any of these problems?

  • “I want to customize the KPI functions in this chapter to suit my company’s product line and indicators.”
  • “I want to rebuild the data pipeline that stops at CSV into a robust processing flow.”
  • “I want to automate order calculation and schedule management using Python”
  • “I would like you to teach Python using actual field data during in-house training.”

Services provided

ServiceOverview
Python training for the manufacturing industryPractical training using field data (online/face-to-face)
KPI automatic aggregation system developmentAutomated pipeline for defect rate, utilization rate, and profit calculation
Data cleansing infrastructure constructionSafe preprocessing flow for sensor/CSV data
DX promotion consultingConsistent support from problem resolution to implementation and establishment support

📩 Contact: www.surikobo.co.jp/contact Please feel free to contact us first.