Solution (source code)

= Solution

After $n$ tosses, the next total is even if either the current total is even and a tail occurs, or the current total is odd and a head occurs. Therefore
$$
q_{n+1}=(1-p)q_n+p(1-q_n)
=p+(1-2p)q_n.
$$
Since $q_0=1$, subtracting the fixed point $1/2$ gives
$$
q_{n+1}-\frac12
=(1-2p)\left(q_n-\frac12\right).
$$
Thus
$$
\boxed{
q_n=\frac{1+(1-2p)^n}{2}}.
$$
The formula also covers the endpoint cases $p=0$ and $p=1$.