Prove that the inverse image of an open set is open
Take $x_0\in f^{-1}(M)$, then $f(x_0)\in M$.
Since $M$ is open, there exists $r>0$ such that $B(f(x_0),r)\subset M$.
Now, choose any $0<\varepsilon\leq r$, since $f$ is continuous, there exists $\delta>0$ such that $f(x)\in B(f(x_0),\epsilon)$ whenever $x\in B(x_0,\delta)$.
Note that if $x\in B(x_0,\delta)$, then $f(x)\in B(f(x_0),\varepsilon)\subset M$, thus $f(x)\in M$, moreover, $x\in f^{-1}(M)$, thus $B(x_0,\delta)\subset f^{-1}(M)$, then $f^{-1}(M)$ is open.
Suppose $f:X \to \mathbb{R}$ is a continuous function and $M \subset \mathbb{R}$ is an open set. Let $x_0 \in f^{-1}(M)$, then $f(x_0) \in M$, which is open, so $\exists \epsilon > 0$ such that $B_{\epsilon}(f(x_0)) \subseteq M$. As $f$ is continuous, $\exists \delta_{\epsilon} > 0$ so that $|x-x_0| < \delta_{\epsilon} \Rightarrow |f(x)-f(x_0)| < \epsilon$. Claim $B_{\delta_{\epsilon}}(x_0) \subseteq f^{-1}(M)$. Indeed, let $p \in B_{\delta_{\epsilon}}(x_0)$, then $|p-x_0| < \delta_{\epsilon} \Rightarrow |f(p)-f(x_0)| < \epsilon \iff f(p) \in B_{\epsilon}(f(x_0)) \subseteq M$, so $f(p) \in M \iff p \in f^{-1}(M)$ $\\$ Thus $B_{\delta_{\epsilon}}(x_0) \subseteq f^{-1}(M)$, namely $f^{-1}(M)$ is open