1from math import comb2n, p, k = 4, 0.3, 13ways = comb(n, k)4round(ways * p**k * (1-p)**(n-k), 4)nptry 1try 2try 3try 4X=0X=1X=2X=3X=4E[X] = 2E[X] = 1.20
Try and parameter cells: the four tries, n and pBars: P(X = k) for each number of successes kCalculator: the current count or sumPython card: the binomial formula with math.combFour independent yes/no tries, each a success with chance p. The four try cells stand for the tries and the two parameter cells hold n and p. With p = 1/2, each of the 16 sequences has chance 1/16; the number of sequences with k successes, C(4, k), drops that many 1/16 blocks on column k, so the bars grow to 1, 4, 6, 4 and 1: the Binomial(4, 1/2) distribution. The tags show P(X = k), then the running totals P(X ≤ k), and a wedge marks the mean np = 2. When p changes to 0.3 the same formula reshapes the bars, and 10,000 random draws land close to them. For large n the binomial bars hug a bell curve, the normal distribution with mean np and standard deviation √(np(1 − p)). This is the de Moivre–Laplace theorem, a special case of the central limit theorem.

From one try to many

  1. Some distributions come up so often they have names. The simplest is one yes/no try that succeeds with chance p. X is 1 on success, 0 otherwise: a Bernoulli(p) variable. A fair coin flip, heads = 1, is Bernoulli(1/2).

The binomial distribution

Parameters and samples

Try it in the Python prompt

;; step 1/9 · One try: Bernoulli
>>> import random
>>> random.seed(1)
>>> [int(random.random() < 0.5) for _ in range(10)]   # ten Bernoulli(1/2) draws
[1, 0, 0, 1, 1, 1, 0, 0, 1, 1]

X ~ Binomial(n, p) is read "X follows a binomial distribution with n tries and success chance p". C(n, k) = n! / (k! (n − k)!) is the number of ways to choose k items from n. random.binomialvariate was added in Python 3.12. On older versions, sum(random.random() < p for _ in range(n)) draws the same distribution.