Compute P(X=k) for a Binomial(n, p) distribution: the probability of exactly k successes in n independent trials each with success probability p. Formula: C(n,k) × p^k × (1−p)^(n−k). Show each piece as a named variable — the binomial coefficient via math.comb, the success probability mass p^k, the failure probability mass (1−p)^(n−k) — then multiply. Library: scipy.stats.binom.pmf(k, n, p).

By hand

Four named pieces make the formula readable: comb=math.comb(5,2)=10, pk=0.5²=0.25, q=1−0.5=0.5, q_nk=0.5³=0.125. Multiply: prob = 10 × 0.25 × 0.125 = 0.3125. Each piece is visible in the trace before the final product.

naive.py
Replay: real traced execution (multi-file project)
import math
n = 5
k = 2
p = 0.5
comb = math.comb(n, k)
pk = p ** k
q = 1 - p
q_nk = q ** (n - k)
prob = comb * pk * q_nk
print('RESULT:', round(prob, 6))
  1. import math

    1import math2n = 5
  2. n ← 5

    1import math2n = 53k = 2
    values this step5n
  3. k ← 2

    2n = 53k = 24p = 0.5
    values this step2k
  4. p ← 0.5

    3k = 24p = 0.55comb = math.comb(n, k)
    values this step0.5p
  5. comb ← 10

    4p = 0.55comb = math.comb(n, k)6pk = p ** k
    values this step10comb
  6. pk ← 0.25

    5comb = math.comb(n, k)6pk = p ** k7q = 1 - p
    values this step0.25pk
  7. q ← 0.5

    6pk = p ** k7q = 1 - p8q_nk = q ** (n - k)
    values this step0.5q
  8. q_nk ← 0.125

    7q = 1 - p8q_nk = q ** (n - k)9prob = comb * pk * q_nk
    values this step0.125q_nk
  9. prob ← 0.3125

    8q_nk = q ** (n - k)9prob = comb * pk * q_nk10print('RESULT:', round(prob, 6))
    values this step0.3125prob
  10. stdout ← RESULT: 0.3125

    9prob = comb * pk * q_nk10print('RESULT:', round(prob, 6))
    values this stepRESULT: 0.3125stdout

With the library

scipy.stats.binom.pmf(k, n, p) applies the same formula internally. Parameters are (k, n, p) — note the order: k first, then the distribution parameters n and p.

library.py
from scipy.stats import binom
from dalib.display import set_display
set_display()

n = 5
k = 2
p = 0.5
prob = binom.pmf(k, n, p)
print('n:', n, ' k:', k, ' p:', p)
print('RESULT:', round(prob, 6))
n: 5  k: 2  p: 0.5
RESULT: 0.3125

Implementation notes

  • C(n,k) counts the number of distinct arrangements of k successes among n trials. math.comb(n, k) computes this exactly in integer arithmetic with no floating-point error.
  • p=0.5 makes the exact-fraction result 0.3125 visible without rounding. The result is exact because 0.5 is representable in binary float.
  • The binomial distribution assumes independence between trials and a constant p. Relaxing independence leads to more complex models.
  • Cross-reference: poisson-probability (this chapter) — the Poisson distribution is the limit of Binomial(n, λ/n) as n→∞ with fixed λ.