To say that a smooth, closed manifold $N$ is obtained by surgery along a (framed) sphere in $M$ is to say that there is a cobordism $P$ from $M$ to $N$ and a Morse function $f\colon P\to [0,1]$, with $f^{-1}(0)=M$, $f^{-1}(1)=N$, and exactly one critical point $c$. By Morse theory, $H_*(P,M)$ is then 1-dimensional, generated by the descending disc of $c$. Likewise, $H_*(P,N)$ is 1-dimensional, generated by the ascending disc of $c$.

By the homology exact sequence of the pair $(P,M)$, $\dim H_*(M)$ differs from $\dim H_*(P)$ by $1$. By the homology exact sequence of the pair $(P,N)$, $\dim H_*(N)$ also differs from $\dim H_*(P)$ by $1$. Hence $|\dim H_*(M) - \dim H_*(N)|$ is $0$ or $2$.