Lab · Programming · 5 sections

Python for statistical analysis

Write a Python function with explicit rules for missing and invalid outcomes, then test its boundaries.

No account needed to read online.

What it covers

  • Specify the function
  • Separate calculation from display
  • Check three small examples
  • Practice with an invalid input

Can your function tell zero from missing?

Run the five tests. Find the line that drops observed zeros, repair it, and run the tests again.

Read online

Python for statistical analysis

Specify the function

Project brief. Recreate the same person-level analysis in Python 3. The function accepts only 0, 1, and None. It returns event count, observed count, missing count, and the observed-outcome proportion. Define behavior for invalid values and for a dataset with no observed outcomes before implementing.

Separate calculation from display

Keep calculation separate from printing. This makes the function reusable and lets tests check values directly. The accepted values are explicitly constrained so values such as 2 fail early.

def summarise_risk(values):
    if any(value not in (0, 1, None) for value in values):
        raise ValueError("Expected 0, 1, or None")
    observed = [value for value in values if value is not None]
    events = sum(observed)
    n_observed = len(observed)
    risk = events / n_observed if n_observed else None
    return {
        "events": events,
        "observed": n_observed,
        "missing": len(values) - n_observed,
        "risk": risk,
    }

Check three small examples

Run these assertions after defining the function. They check the primary example, an observed zero, all outcomes missing, and invalid input. The common shortcut that keeps truthy values is wrong because it discards zero as well as None.

outcomes = [1, 0, None, 0, 1]
result = summarise_risk(outcomes)
assert result == {
    "events": 2, "observed": 4, "missing": 1, "risk": 0.5
}
assert summarise_risk([0, None])["risk"] == 0.0
assert summarise_risk([None, None])["risk"] is None
try:
    summarise_risk([1, 2])
except ValueError:
    pass
else:
    raise AssertionError("Invalid outcome was accepted")

Practice with an invalid input

Call summarise_risk([1, 2]). Expect a ValueError. Now test an empty list and predict the result before running it. Both inputs have zero observed outcomes and undefined risk. The missing count is 0 for an empty list and 2 for [None, None].

Extend it with pytest

Place the function in analysis.py and tests in test_analysis.py. Run python -m pytest. Add a test for an empty list and one for a duplicated participant ID if the function is extended to accept records. The test should express the data contract, not duplicate the function implementation.

Discussion

Questions, clarifications and applications of this resource.

Loading discussion…