Solution (source code)

= Solution

For a nonnegative integer-valued <random variable> $X$, its <probability generating function> is
$$
G_X(z)=\mathbb E[z^X]=\sum_{k=0}^{\infty}\mathbb P(X=k)z^k,
$$
initially defined at least for $|z|\le1$. A general real-valued random variable need not have a <probability generating function> in this sense. For a <binomial distribution>, the <binomial theorem> gives
$$
G_X(z)=\sum_{k=0}^n\binom nkp^k(1-p)^{n-k}z^k=(1-p+pz)^n.
$$
Differentiating the generating function produces factorial moments:
$$
\mathbb EX=G_X'(1)=np,\qquad
\mathbb E[X(X-1)]=G_X''(1)=n(n-1)p^2.
$$
Since $X^2=X(X-1)+X$, the <mean> and <variance> are
$$
\boxed{\mathbb EX=np,\qquad\operatorname{Var}(X)=np(1-p).}
$$
These formulas include the degenerate endpoint <probabilities> and $n=0$.