Random variables
Flip a fair coin three times. There are 2 × 2 × 2 = 8 possible outcomes, from HHH to TTT. All are equally likely, so each has probability 1/8. The set of every outcome is the sample space.
A random variable is a rule that gives every outcome a number. Let X count the heads: HHT gives 2 and TTT gives 0. The rule itself is fixed; the chance lies in which outcome happens.
Distributions
Group the outcomes by their value of X. Each drops a 1/8 block on its column: one block at 0 heads, three at 1, three at 2, one at 3. The list of P(X = x) is the distribution of X.
Exactly one outcome happens on every try, so a distribution always adds up to 1: 1/8 + 3/8 + 3/8 + 1/8 = 8/8 = 1. One head and two heads are the most likely values.
Expectation
The expected value E[X] weights each value by its probability, then adds: 0 × 1/8 + 1 × 3/8 + 2 × 3/8 + 3 × 1/8 = 12/8 = 1.5. It is the long-run average of X over many tries.
Picture the blocks as weights on a beam. E[X] = 1.5 is the point where the beam balances. It need not be a value X can take: no single try gives one and a half heads.
Or split X: X = X1 + X2 + X3, where Xk is 1 if flip k is heads, else 0. Each flip is heads in 4 of 8 outcomes, so E[Xk] = 1/2. Expectations add: E[X] = 1/2 + 1/2 + 1/2 = 1.5.
Spread and samples
Variance measures spread: Var(X) = E[X²] − (E[X])². Here E[X²] = (0 + 3 + 12 + 9)/8 = 3, so Var(X) = 3 − 1.5² = 0.75. Its square root, the standard deviation, is about 0.87.
Now simulate it. With random.seed(1), Python's average of X is 1.9 after 10 tries, 1.5 after 100 and 1.4937 after 10,000. The law of large numbers says the average settles near E[X] = 1.5.
In code, list the sample space with itertools.product, apply X to every outcome and take the mean. All 8 outcomes are equally likely, so sum(X) / len(S) is exactly E[X] = 1.5.
Try it in the Python prompt
;; step 1/10 · Three flips, eight outcomes
>>> from itertools import product
>>> S = list(product('HT', repeat=3))
>>> len(S), S[0], S[-1]
(8, ('H', 'H', 'H'), ('T', 'T', 'T'))
Capital X names the random variable; small x stands for one of its values. P(X = x) is the probability that X takes the value x. Linearity of expectation, E[X + Y] = E[X] + E[Y], holds for any random variables, even ones that depend on each other. Variances only add like this when the variables are independent.