Appendix B — A Beginner’s Guide to Python
This appendix assumes no prior programming experience. Work through the sections in order, type each example, predict its output, and compare the result with the explanation. The examples parallel Appendix A so that readers can compare R and Python without changing the scientific question. Code blocks in this appendix are illustrative; the companion script and report are executable.
B.1 Getting started
Python is a general-purpose language. The interpreter executes instructions; an editor helps you write them; Jupyter maintains a computational kernel. A Quarto document combines prose and executable cells. Install Python from python.org and Quarto separately. Use a terminal, not the Python prompt, for the following commands. On Windows, use py if python is not available.
python -m venv .venv
# Windows PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install numpy pandas matplotlib scipy statsmodels jupyter
quarto check jupyterCheck the interpreter using python –version and identify its path using sys.executable. If activation is restricted, invoke the environment interpreter directly.
B.2 Variables and arithmetic
Assignment binds a name to a value. Python is case sensitive. Use descriptive names and keep measurement units in comments or variable names. Division produces a floating-point result; exponentiation uses **, not ^. Parentheses clarify the intended order.
initial = 80
k = 0.2
time = 5
import math
concentration = initial * math.exp(-k * time)
print(round(concentration, 2))Predict the result when time is zero. Then calculate concentration after ten hours. The model is hypothetical, not a clinical dosing recommendation.
B.3 Collections and indexing
Lists preserve order and can be changed. Tuples are immutable sequences. Dictionaries associate keys with values. Python indexing begins at zero; slices exclude their upper endpoint. A list multiplied by an integer repeats its contents rather than multiplying each value.
wait = [10, 12, 15, 18, 25]
print(wait[0], wait[-1], wait[1:4])
appointment = {"clinic": "A", "wait": 10}
print(appointment["wait"])
print([2*x for x in wait])Extract the last three observations and calculate their sum. Explain why wait * 2 is not a numerical scaling operation.
B.4 Data types and missing values
Integers, floats, strings and Boolean values represent different kinds of information. None represents absence in ordinary Python; NumPy uses nan for missing floating-point measurements. A missing measurement is not a zero. Explicit conversion is useful when reading text, but invalid values should be investigated rather than silently replaced.
import numpy as np
x = np.array([10, 12, np.nan, 18])
print(np.isnan(x))
print(np.nanmean(x))
print(type("12"), type(float("12")))Count observed and missing values in x. Explain why replacing the missing value with zero changes the mean.
B.5 NumPy and mathematical functions
NumPy arrays support elementwise numerical operations. Use linspace when the number of grid points matters. Unlike arange with floating increments, linspace can explicitly include both endpoints. Vectorization expresses a mathematical function over an entire grid.
import numpy as np
t = np.linspace(0, 10, 21)
C = 80 * np.exp(-0.2*t)
print(C[0], C[-1])
print(np.log(2)/0.2)Find the half-life and verify numerically that the concentration at that time is 40.
B.6 Matrices and linear systems
A two-dimensional array represents rows and columns. The @ operator performs matrix multiplication, whereas * performs elementwise multiplication. Solve a nonsingular system directly rather than explicitly computing an inverse. Check the residual to verify the solution.
A = np.array([[2, 1], [1, 3]])
b = np.array([5, 7])
x = np.linalg.solve(A, b)
print(x)
print(A @ x - b)Verify the solution by substitution. Explain why a singular coefficient matrix cannot be handled by this direct solver.
B.7 Data frames and importing data
A pandas DataFrame stores labeled columns of potentially different types. Each row in the supplied synthetic clinic file is one appointment. The columns record clinic, waiting time in minutes, sleep in hours and systolic blood pressure. Run the examples from examples/appendix-b, where clinic.csv is located. Inspect dimensions and column types before analyzing.
import pandas as pd
clinic = pd.read_csv("clinic.csv")
print(clinic.head())
print(clinic.dtypes)
print(clinic.shape)
print(clinic.isna().sum())
assert clinic.id.is_uniqueIdentify the observational unit, number of records and missing waiting-time measurements. Do not publish identifiable patient records.
B.8 Filtering and transformation
Boolean masks select rows. Use loc for explicit row and column selection. Make a copy before adding a derived variable to a subset. A threshold in this exercise is an instructional classification, not a clinical decision rule.
a = clinic.loc[clinic["clinic"] == "A"].copy()
a["wait_hours"] = a["wait"] / 60
print(a[["id", "wait_hours"]])
print(clinic.loc[clinic.wait > 15, ["id", "wait"]])Count appointments with observed waiting times above 15 minutes. Explain why missing observations are not included in this count.
B.9 Descriptive statistics
Pandas mean and standard deviation omit missing values by default. Report the number observed as well as the total number of records. The sample standard deviation uses n minus one by default in pandas, unlike NumPy std. Specify ddof=1 when using NumPy for a sample standard deviation.
print(clinic.wait.describe())
print(clinic.groupby("clinic").wait.agg(["size", "count", "mean", "median", "std"]))
print(clinic.wait.isna().mean())Compare clinic means and missingness. Explain why the observed difference is not necessarily a causal effect.
B.10 Statistical graphics
Matplotlib separates the figure from its axes. Use explicit labels, units, and readable text. A dot plot is especially useful for a small dataset because it preserves individual observations. Save a figure before displaying it. Avoid decorative frames and unnecessary color.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 3))
for i, (name, group) in enumerate(clinic.groupby("clinic")):
ax.scatter(group.wait.dropna(), [i]*group.wait.count(), label=name)
ax.set(yticks=[0, 1], yticklabels=["A", "B"], xlabel="Waiting time (minutes)", ylabel="Clinic")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("waiting-times.png", dpi=300)
plt.show()Create a scatterplot of sleep and systolic blood pressure. Label both axes and describe the association without making a causal claim.
B.11 Functions and control flow
A function accepts arguments and returns a result. Indentation defines blocks. Validate inputs to prevent meaningless computations. A loop is appropriate for repeated tasks; array operations are often clearer for numerical calculations.
def half_life(k):
if k <= 0:
raise ValueError("k must be positive")
return np.log(2)/k
for rate in [0.1, 0.2, 0.4]:
print(rate, half_life(rate))Write a function that returns concentration for nonnegative time and positive decay rate. Test its value at zero.
B.12 Probability and simulation
A pseudorandom generator produces reproducible sequences when initialized with a seed. Simulate repeated independent samples to explore a sampling distribution. The empirical standard deviation of simulated means approximates the theoretical standard error; the two need not agree exactly.
rng = np.random.default_rng(2026)
samples = rng.normal(20, 6, size=(2000, 25))
means = samples.mean(axis=1)
print(means.std(ddof=1), 6/np.sqrt(25))Repeat with sample size 100. Predict the theoretical standard error before running the simulation.
B.13 Statistical inference and modeling
SciPy provides probability distributions and hypothesis tests. Here the Welch test compares observed waiting times under an illustrative independent-samples assumption. The small synthetic dataset cannot establish clinical effectiveness. A regression of blood pressure on sleep is descriptive; confounding and model assumptions matter.
from scipy import stats
a = clinic.loc[clinic.clinic == "A", "wait"].dropna()
b = clinic.loc[clinic.clinic == "B", "wait"].dropna()
print(stats.ttest_ind(a, b, equal_var=False))
import statsmodels.formula.api as smf
model = smf.ols("sbp ~ sleep", data=clinic).fit()
print(model.params)
print(model.conf_int())Interpret the slope in mmHg per hour. State two limitations of this analysis and distinguish association from causation.
B.14 Packages and reproducibility
Install packages into a dedicated virtual environment. Record Python and package versions, and use relative paths. A requirements file lists dependencies; a frozen environment records exact installed versions but may contain platform-specific packages. Never commit the virtual environment itself.
python -m pip freeze > requirements-lock.txt
python -m pip install -r requirements.txt
quarto check jupyterExplain the difference between a dependency list and an exact environment snapshot. Add .venv/ to .gitignore.
B.15 Integrating Python with Quarto
Create a file named report.qmd. YAML identifies the output format and Jupyter kernel. A fenced cell with braces is executable; a plain Python fence displays source only. The label and caption options associate a figure with a cross-reference. Render from the directory containing the data. A clean render should not depend on variables left in an interactive notebook.
---
title: "Clinic waiting-time analysis"
format: html
jupyter: python3
---
```{python}
import pandas as pd
clinic = pd.read_csv("clinic.csv")
clinic.groupby("clinic").wait.mean()
```
Run quarto render report.qmd --to html. If the wrong kernel is selected, inspect quarto check jupyter and the available kernels with jupyter kernelspec list. The companion report contains a labeled figure and an explicit missing-data summary.
B.16 Applied project: Reproducible clinic summary
Develop a report for a hypothetical clinic manager. State the question and identify the observational unit. Import the supplied dataset, validate unique IDs, report missingness, and calculate observed waiting-time summaries by clinic. Produce a dot plot and a sleep–blood pressure scatterplot. Explain the observed patterns, limitations, and why these synthetic observations do not support causal conclusions. Submit the source, dataset, rendered HTML and environment instructions. Compare the observed means against Appendix A.
| Criterion | Points |
|---|---|
| Data import and validation | 5 |
| Correct descriptive analysis | 5 |
| Appropriate statistical graphics | 5 |
| Interpretation and limitations | 5 |
| Reproducible Quarto source | 5 |
| Total | 25 |