The t-test, and what a p-value says
- Compute a t statistic and its degrees of freedom by hand, and say why t has heavier tails than z
- Compare two groups with Welch's t-test, and test pairs as differences
- Explain a p-value correctly in two sentences, and name the four things it isn't
- Check a test with a permutation test, which assumes no shape
- Correct for many tests at once with Bonferroni, Holm or Benjamini-Hochberg
t-tests and p-values, the way the statistics round asks
A Netflix data science candidate had to compute a t statistic in the statistics round (1 report), and an OpenAI round asked how you would explain a p-value (1 report). This lesson's practice problem puts both in code, with only the standard library, in three levels:
one_sample_t(xs, mu0)andwelch_t(xs, ys): each t statistic, and its degrees of freedom.paired_t(xs, ys)on the differences, andt_p_value(t, df): the two-sided p-value from Student's t curve.permutation_p(xs, ys, reps, seed), thenbonferroni,holmandbenjamini_hochberg, each returning the indices of the p-values it rejects.
Call Returns the t for 16 deliveries averaging 4.6 days, with a standard deviation of 0.8, against a promised 4.0 t = 3.0, with 15 degrees of freedom t_p_value(3.0, 15)0.0090 paired_t([5, 7, 6, 9], [4, 5, 5, 6])t = 3.66, with 3 degrees of freedom benjamini_hochberg([0.002, 0.02, 0.04, 0.3], 0.05)[0, 1]Then tell me what a p-value is, and what it isn't.
The lesson builds each piece on one running example, a shop's delivery carriers: t against z, Welch's test, pairs, what a p-value says, a permutation test, and three corrections for many tests. Six steps end with a small task in the editor. It builds on the distributions lesson and its central limit theorem.
When the spread is estimated from the data, use t, not z
A Netflix data science candidate had to compute a t statistic in the statistics round (1 report). The t statistic for one sample is the gap between its mean and a claimed value, in standard errors:
The shop's new carrier promises deliveries in 4.0 days on average. The first 25 deliveries average 4.4 days, with a standard deviation of 1.0.
What's the t statistic for those 25 deliveries against the promised 4.0 days?
Estimating the spread makes the tails heavier
The z-test in the A/B testing lesson treats the standard error as known. NIST's handbook notes that the more typical case is where the standard deviation must be estimated from the data, and that estimate is itself noisy.
William Sealy Gosset worked this out as a brewer at Guinness in Dublin. His contract barred him from publishing under his own name, so his 1908 paper went out under the pseudonym Student. He warned that with fewer experiments the estimated standard deviation carries more error, until judgments made with it can become altogether misleading.
His answer was the t distribution: shaped like the normal, NIST says, but with heavier tails. It has degrees of freedom, n − 1 for one sample, and approaches the normal as they grow, quite good past 30.
- p from the t curve
- 0.102
- p from the normal
- 0.046
- t's 5% cutoff
- ±2.57
- Normal's cutoff
- ±1.96
import math
from statistics import NormalDist
def t_pdf(x: float, df: float) -> float:
"""Student's t density with df degrees of freedom."""
c = math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(df * math.pi)
return c * (1 + x * x / df) ** (-(df + 1) / 2)
def t_two_sided_p(t: float, df: float, steps: int = 2_000) -> float:
"""The area beyond -|t| and +|t|: 1 minus Simpson's rule on -|t| to |t|."""
h = abs(t) / steps
inner = t_pdf(0, df) + t_pdf(abs(t), df)
inner += sum((4 if i % 2 else 2) * t_pdf(i * h, df) for i in range(1, steps))
return 1 - 2 * inner * h / 3
# 25 deliveries: average 4.4 days, standard deviation 1.0
n, mean, s = 25, 4.4, 1.0
# against the carrier's promised 4.0 days
t = (mean - 4.0) / (s / math.sqrt(n))
print(f"t = {t:.2f} with {n - 1} degrees of freedom")
print(f"p from the t curve: {t_two_sided_p(t, n - 1):.4f}")
print(f"p from the normal curve: {2 * (1 - NormalDist().cdf(t)):.4f}")
Is the 0.4-day gap significant at the 5% level?
Two groups get Welch's test
NIST's handbook says the two-sample t-test decides whether two population means are equal. The shop is choosing between two carriers: carrier A delivered 40 parcels, averaging 4.1 days with a standard deviation of 1.2, and carrier B delivered 30, averaging 3.6 days with a standard deviation of 0.6.
Carrier A's spread is twice carrier B's. What should the standard error of the gap use?
Pairs: test the differences
NIST calls two samples paired when there's a one-to-one correspondence between their values. Say both carriers run the same 12 routes. Some routes are slow for everyone, so the route matters more than the carrier, and two-group tests count that route-to-route spread as noise.
from statistics import mean, stdev
# carrier A on 12 routes
a = [2.9, 3.2, 3.6, 4.0, 4.4, 4.3, 4.9, 5.2, 5.4, 5.9, 6.2, 6.7]
# carrier B on the same routes
b = [2.6, 3.1, 3.1, 3.9, 4.1, 3.9, 4.4, 5.0, 5.3, 5.4, 6.1, 6.2]
t_u, df_u = welch(mean(a), stdev(a), len(a), mean(b), stdev(b), len(b))
t_p, df_p = paired_t(a, b)
print(f"as two groups: t = {t_u:.2f}, p = {t_two_sided_p(t_u, df_u):.3f}")
print(f"as pairs: t = {t_p:.2f}, p = {t_two_sided_p(t_p, df_p):.6f}")
Carrier A is 0.3 days slower on every route, give or take a little. Which analysis sees it?
A p-value measures how surprising the data are under one model
An OpenAI round asked how you would explain a p-value (1 report). The American Statistical Association's 2016 statement gives the definition: informally, the probability under a specified model that a summary of the data would be equal to or more extreme than its observed value. It's a statement about the data in relation to a hypothetical explanation, not about the explanation itself.
The same statement lists what a p-value can and can't do:
- It can show how incompatible the data are with a specified model.
- It doesn't measure the probability that the hypothesis is true, or that chance alone produced the data.
- Decisions shouldn't rest only on whether it passes a threshold.
- It doesn't measure the size of an effect or how much it matters.
The carrier test gave p = 0.057. Which sentence is right?
If nothing is going on, p-values are spread evenly
What do p-values look like when the null is true? Here are 2,000 tests of two groups drawn from the same distribution:
import random
rng = random.Random(9)
ps = []
for _ in range(2_000):
x = [rng.gauss(4, 1) for _ in range(20)]
# the same distribution: no real difference
y = [rng.gauss(4, 1) for _ in range(20)]
t, df = welch(mean(x), stdev(x), 20, mean(y), stdev(y), 20)
ps.append(t_two_sided_p(t, df, steps=200))
print(f"{sum(p < 0.05 for p in ps) / len(ps):.1%} of the p-values fall below 0.05")
print("by tenths:", [sum(k / 10 <= p < (k + 1) / 10 for p in ps) for k in range(10)])
With no real difference anywhere, how many of the 2,000 tests come out below 0.05?
A test on 2 million users finds a 0.1% lift in orders with p = 0.0001. What does the p-value tell you?
A permutation test checks the answer without assuming a shape
The t-test leans on the CLT, and the distributions lesson showed how slowly that works for skewed order values. A permutation test needs no shape. If the two groups really come from the same distribution, which SciPy's docs give as the null, then the labels don't matter, so shuffle them. The p-value counts how many shuffled gaps are at least as extreme as the real one.
Here are 15 orders a side from an old and a new checkout, with order values skewed like the shop's:
rng = random.Random(10)
# order values, old checkout
old = [round(math.exp(rng.gauss(4, 1)), 2) for _ in range(15)]
# order values, new checkout
new = [round(math.exp(rng.gauss(4.4, 1)), 2) for _ in range(15)]
t, df = welch(mean(new), stdev(new), 15, mean(old), stdev(old), 15)
print(f"means ${mean(old):.0f} and ${mean(new):.0f}")
print(f"Welch p = {t_two_sided_p(t, df):.3f}, permutation p = {permutation_p(new, old, 10_000, rng):.3f}")
The new checkout's average order is far higher. With 15 skewed orders a side, is that convincing?
Test twenty metrics at 5%, and something will look significant
The shop's dashboard tests 20 metrics for every change. If the change does nothing, each still has a 5% chance of a false alarm.
20 metrics, none really affected, each tested at 5%. What's the chance at least one looks significant?
Which correction fits a screen of 200 product metrics, where a few false leads are fine as long as most finds are real?
Holm rejects at least as much as Bonferroni
Bonferroni holds every p-value to the strictest bar, α/m. Holm's method relaxes the bar as it goes. Sort the p-values, compare the smallest with α/m, the next with α/(m − 1), and so on. A p-value at most its bar is rejected, and the first one above its bar stops the walk. It rejects everything Bonferroni rejects, and it still keeps the chance of any false alarm at α.
Three metrics come back with p-values of 0.01, 0.015 and 0.04, at α = 0.05:
| Rank | p | Holm's bar, α/(m − k + 1) | Bonferroni's bar, α/m |
|---|---|---|---|
| 1 | 0.01 | 0.0167: rejected | 0.0167: rejected |
| 2 | 0.015 | 0.025: rejected | 0.0167: rejected |
| 3 | 0.04 | 0.05: rejected | 0.0167: kept |
Holm finds all three, and Bonferroni finds two. The stop matters: once a p-value misses its bar, every larger one is kept, even if it would clear a later bar.
In the editor, write holm(ps, alpha). It prints what Holm rejects for the three metrics above.
Benjamini-Hochberg keeps the largest rank that passes
Benjamini-Hochberg works on ranks too, with a different rule: it finds the largest rank whose p-value is at most k/m × q, and rejects everything up to it, even past an earlier miss.
Four p-values at q = 0.05:
| Rank k | p | Bar, k/m × q | |
|---|---|---|---|
| 1 | 0.01 | 0.0125 | passes |
| 2 | 0.03 | 0.025 | misses |
| 3 | 0.035 | 0.0375 | passes |
| 4 | 0.5 | 0.05 | misses |
The largest rank that passes is 3, so the three smallest are rejected, the 0.03 included. Holm would have stopped at rank 2.
In the editor, write benjamini_hochberg(ps, q). It prints what it rejects for the dashboard's ten p-values.
Compute the t statistic
Here's a statistics round question, worked out loud.
16 users in a test watched 52 minutes on average, with a standard deviation of 12. The usual average is 45. Is that a real change?
1. Name the test: one sample, spread estimated, so t with 15 degrees of freedom.
2. Compute: standard error 12 / √16 = 3, so t = 7 / 3 = 2.33.
t = (52 - 45) / (12 / math.sqrt(16))
print(f"t = {t:.2f} with 15 degrees of freedom, p = {t_two_sided_p(t, 15):.3f}")
Is the jump from 45 to 52 minutes significant at 5%?
Explain a p-value
The same round often asks for words, not numbers.
How would you explain a p-value to a product manager?
Take the last question's p of 0.034. Two sentences: if the change did nothing, a gap at least this big would show up in 3.4% of tests like this one. That's rare enough that we doubt the change did nothing.
The product manager asks: so there's a 96.6% chance it works? What's the best reply?
One-sided tests
Two follow-ups come up after a t-test.
A one-sided test puts the whole 5% in one tail, which only makes sense if you chose that direction before seeing the data and would act the same way on an effect the other way. Otherwise it halves your p-value for nothing.
A two-sided test gives p = 0.08. Someone suggests switching to one-sided after the fact to get 0.04. What's the problem?
Pre-testing the variances
Testing whether the variances are equal and then picking Student's or Welch's test sounds careful, and Delacre and colleagues found it often fails. Use Welch's test from the start.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.25 deliveries average 4.4 days with a standard deviation of 1.0. What's the t statistic against 4.0, and its degrees of freedom?
2.Why does t have heavier tails than the normal?
3.Which statement about p = 0.03 is right?
4.The same 12 routes ran with both carriers. Which test fits?
5.You test 10 metrics and want most of your finds to be real, not zero false alarms. Which correction fits?
Practice
Sources (26)
- 7.2.2. Are the data consistent with the assumed process mean? · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The more typical case is where the standard deviation must be estimated from the data”
- Gosset, William Sealy [pseud. Student] (Oxford DNB article) · M. Eileen Magnello, Oxford University Press, on MacTutor (University of St Andrews) · Nov 19, 2026
“In October 1899 he became a brewer with Arthur Guinness, Son & Co., Ltd, manufacturers of stout at the St James's Gate Brewery in Dublin.”
- Gosset, William Sealy [pseud. Student] (Oxford DNB article) · M. Eileen Magnello, Oxford University Press, on MacTutor (University of St Andrews) · Nov 19, 2026
“He was bound by his appointment not to publish in his own name, and this led to his subsequent adoption of the pseudonym Student.”
- The Probable Error of a Mean · Student, Biometrika (retyped copy hosted by the University of York) · Mar 1, 1908
“as we decrease the number of experiments, the value of the standard deviation found from the sample of experiments becomes itself subject to an increasing error, until judgments reached in this way may become altogether misleading.”
- 1.3.6.6.4. t Distribution · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The difference is in the heaviness of the tails.”
- 1.3.6.6.4. t Distribution · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The t distribution approaches a normal distribution as ν becomes large. The approximation is quite good for values of ν > 30.”
- 1.3.5.3. Two-Sample t-Test for Equal Means · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The two-sample t-test (Snedecor and Cochran, 1989) is used to determine if two population means are equal.”
- 1.3.5.3. Two-Sample t-Test for Equal Means · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The Welch-Satterthwaite degrees of freedom are robust for unequal sample sizes and/or unequal variances.”
- Why Psychologists Should by Default Use Welch's t-test Instead of Student's t-test · Delacre, Lakens and Leys, International Review of Social Psychology · Apr 5, 2017
“We show that the Welch's t-test provides a better control of Type 1 error rates when the assumption of homogeneity of variance is not met, and it loses little robustness compared to Student's t-test when the assumptions are met.”
- Why Psychologists Should by Default Use Welch's t-test Instead of Student's t-test · Delacre, Lakens and Leys, International Review of Social Psychology · Apr 5, 2017
“choosing between Student's t-test and Welch's t-test based on the outcomes of a test of the equality of variances often fails to provide an appropriate answer.”
- scipy.stats.ttest_ind · SciPy documentation · Nov 19, 2026
“If False, perform Welch's t-test, which does not assume equal population variance”
- 1.3.5.3. Two-Sample t-Test for Equal Means · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“By paired, we mean that there is a one-to-one correspondence between the values in the two samples.”
- The ASA's Statement on p-Values: Context, Process, and Purpose · Wasserstein and Lazar, The American Statistician (copy hosted by UC Berkeley Statistics) · Mar 7, 2016
“Informally, a p-value is the probability under a specified statistical model that a statistical summary of the data (e.g., the sample mean difference between two compared groups) would be equal to or more extreme than its observed value.”
- The ASA's Statement on p-Values: Context, Process, and Purpose · Wasserstein and Lazar, The American Statistician (copy hosted by UC Berkeley Statistics) · Mar 7, 2016
“It is a statement about data in relation to a specified hypothetical explanation, and is not a statement about the explanation itself.”
- American Statistical Association Releases Statement on Statistical Significance and P-Values · American Statistical Association · Mar 7, 2016
“P-values can indicate how incompatible the data are with a specified statistical model.”
- American Statistical Association Releases Statement on Statistical Significance and P-Values · American Statistical Association · Mar 7, 2016
“P-values do not measure the probability that the studied hypothesis is true, or the probability that the data were produced by random chance alone.”
- American Statistical Association Releases Statement on Statistical Significance and P-Values · American Statistical Association · Mar 7, 2016
“Scientific conclusions and business or policy decisions should not be based only on whether a p-value passes a specific threshold.”
- American Statistical Association Releases Statement on Statistical Significance and P-Values · American Statistical Association · Mar 7, 2016
“A p-value, or statistical significance, does not measure the size of an effect or the importance of a result.”
- The ASA's Statement on p-Values: Context, Process, and Purpose · Wasserstein and Lazar, The American Statistician (copy hosted by UC Berkeley Statistics) · Mar 7, 2016
“Any effect, no matter how tiny, can produce a small p-value if the sample size or measurement precision is high enough, and large effects may produce unimpressive p-values if the sample size is small or measurements are imprecise.”
- scipy.stats.permutation_test · SciPy documentation · Nov 19, 2026
“For independent sample statistics, the null hypothesis is that the data are randomly sampled from the same distribution.”
- scipy.stats.permutation_test · SciPy documentation · Nov 19, 2026
“The p-value is calculated by counting the elements of the null distribution that are as extreme or more extreme than the observed value of the statistic.”
- The ASA's Statement on p-Values: Context, Process, and Purpose · Wasserstein and Lazar, The American Statistician (copy hosted by UC Berkeley Statistics) · Mar 7, 2016
“Researchers should disclose the number of hypotheses explored during the study, all data collection decisions, all statistical analyses conducted, and all p-values computed.”
- 7.4.7.3. Bonferroni's method · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
“The Bonferroni method is a simple method that allows many comparison statements to be made (or confidence intervals to be constructed) while still assuring an overall confidence coefficient is maintained.”
- A Simple Sequentially Rejective Multiple Test Procedure · Holm, Scandinavian Journal of Statistics · Jan 1, 1979
“This paper presents a simple and widely applicable multiple test procedure of the sequentially rejective type, i.e. hypotheses are rejected one at a time until no further rejections can be done.”
- Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing · Benjamini and Hochberg, Journal of the Royal Statistical Society Series B · Jan 1, 1995
“It calls for controlling the expected proportion of falsely rejected hypotheses-the false discovery rate.”
- Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing · Benjamini and Hochberg, Journal of the Royal Statistical Society Series B · Jan 1, 1995
“A simple sequential Bonferroni-type procedure is proved to control the false discovery rate for independent test statistics, and a simulation study shows that the gain in power is substantial.”