How to replace $x$ and $x^2$ with different value?
Give the replacement rules in a list:
expr /. {x^2 -> k p + k (k - 1) p^2, x -> k p}
2 k p + (-1 + k) k p^2
If you are calculating the expectation of an expression, use Expectation
or other built-in statistics functions rather than replacements which can be error-prone (which is why you ended up asking the question).
expr = x + x^2;
Expectation[expr, x \[Distributed] BinomialDistribution[k, p]] //
Simplify
(* k p (2 + (-1 + k) p) *)
Alternatively, using TransformedDistribution
and Mean
Mean[TransformedDistribution[expr,
x \[Distributed] BinomialDistribution[k, p]]] // Simplify
(* k p (2 + (-1 + k) p) *)
Verifying that both results are identical,
% === %%
(* True *)
This is entirely equivalent to Bob's answer:
x + x^2 /. x^m_. :> Moment[BinomialDistribution[k, p], m]
2 k p - (1 - k) k p^2