Compute P(X≤k) for a Binomial(n, p) distribution by summing the pmf from i=0 to k. Loop over i in range(k+1), accumulate each term = C(n,i)×p^i× (1−p)^(n−i). For n=5, p=0.5, k=2: three terms (1/32, 5/32, 10/32) sum to 16/32 = 0.5 exactly. Library: scipy.stats.binom.cdf(k, n, p).

By hand

With the library

scipy.stats.binom.cdf(k, n, p) computes the same cumulative sum. Note argument order: k first, then n and p (same as binom.pmf).

naive.py
import math
n = 5
p = 0.5
k = 2
cdf = 0.0
for i in range(k + 1):
    term = math.comb(n, i) * p ** i * (1 - p) ** (n - i)
    cdf = cdf + term
print('RESULT:', round(cdf, 6))
library.py
from scipy.stats import binom
from dalib.display import set_display
set_display()

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

Implementation notes

  • CDF is the sum of pmf values up to and including k: P(X≤k) = Σ P(X=i) for i=0..k. This loop explicitly shows what the CDF adds up.
  • p=0.5 and n=5 make the result exactly 0.5 by symmetry: the binomial is symmetric around n/2=2.5, so P(X≤2) = P(X≥3) = 0.5.
  • For the survival function P(X>k) use binom.sf(k, n, p) or compute 1 − cdf. For a specific interval P(a<X≤b) compute cdf(b)−cdf(a).
  • Cross-reference: binomial-probability (this chapter) for the single pmf term that each loop iteration computes.