Example 4 Given the sequence $\left\{a_{n}\right\}$ with the sum of the first $n$ terms $S_{n}=p^{n}+q(p \neq 0, p \neq 1)$, find the necessary and sufficient condition for the sequence $\left\{a_{n}\right\}$ to be a geometric sequence.
Solve $a_{1}=S_{1}=p+q$, when $n \geqslant 2$, $a_{n}=S_{n}-S_{n-1}=p^{n-1}(p-1)$.
Since $p \neq 0, p \neq 1$, we have $\frac{a_{n+1}}{a_{n}}=\frac{p^{n}(p-1)}{p^{n-1}(p-1)}=p$.
If $\left\{a_{n}\right\}$ is a geometric sequence, then $\frac{a_{2}}{a_{1}}=\frac{a_{n+1}}{a_{n}}=p$, so $\frac{p(p-1)}{p+q}=p$.
Since $p \neq 0$, we have $p-1=p+q$, so $q=-1$.
This is the necessary condition for $\left\{a_{n}\right\}$ to be a geometric sequence.
Next, we prove that $q=-1$ is the sufficient condition for $\left\{a_{n}\right\}$ to be a geometric sequence.
When $q=-1$, $a_{1}=p-1$, which also fits $a_{n}=p^{n-1}(p-1)$.
Thus, $a_{n}=p^{n-1}(p-1)(n \in \mathbf{N})$, i.e., $\frac{a_{n+1}}{a_{n}}=p(n \in \mathbf{N})$, so $\left\{a_{n}\right\}$ is a geometric sequence.
Therefore, $q=-1$ is the necessary and sufficient condition for $\left\{a_{n}\right\}$ to be a geometric sequence.
Comment: After finding the necessary condition, we should also verify whether it is a sufficient condition.