Show a function mapping a metric space to $\mathbb{R}$ is continuous if and only if it is both upper and lower semi-continuous Let $(M,d)$ be a metric space and $f:(M,d)\rightarrow \mathbb{R}$. Show that $f$ is a continuous function if and only if it is both upper and lower semi-continuous.

Definition:

A function is lower semi-continuous if for all $\lambda \in \mathbb{R}$, the set $\{x \in M : f(x) > \lambda \}$ is open in $M$.
A function is upper semi-continuous if for all $\lambda \in \mathbb{R}$, the set $\{x \in M : f(x) < \lambda \}$ is open in $M$.
This is my try to show the "if":
Let $f$ be continuous at $x$ and $y\in M$ so by continuity of $f$ we have the following:
$$
\forall \epsilon >0 \,\,\exists\,\,\delta>0 \,\,\,\text{s.t.} \,\, d(x,y)<\delta \rightarrow|f(x)-f(y)|<\epsilon
$$
So $f(x)<\epsilon+f(y)=\lambda$.
The next step is some how connection between the above and $\{x \in M : f(x) < \lambda \}$. However, mathematically, to me this is a big jump because it says that for $x \in M$ but I have chosen an $x$ at which the function is continuous. Also, I am far from the fact saying preimage of $f(x) < \lambda$ is an open set. Can you complete or revise my proof?
Also, for the "only if" part we can say $f$ is lower semi-continuous so $\{x \in M : f(x) > \lambda \}$ and $f$ is upper semi-continuous so $\{x \in M : f(x) < \lambda \}$ my question is how to come up with an open ball in $M$.
 A: ($\Rightarrow$) For each $x_0\in\{x\in M:f(x)<\lambda\}$, fix $\varepsilon>0$ such that $f(x_0)+\varepsilon<\lambda$. Since f is continuous, you get $\delta>0$ such that
$$
d(x_0,y)<\delta \Rightarrow |f(y)−f(x_0)|<\varepsilon \Rightarrow f(y)<f(x_0)+\varepsilon<\lambda,
$$
so the open ball $B(x_0,\delta)$ is contained in $\{x\in M:f(x)<\lambda\}$. Since this happens for all $x_0\in\{x\in M:f(x)<\lambda\}$, it follows that $\{x\in M:f(x)<\lambda\}$ is open. An analogous argument proves that the sets $\{x\in M:f(x)>\lambda\}$ are open.
($\Leftarrow$):  For each $x_0\in M$ and $\varepsilon>0$, consider the sets $\{x\in M : f(x)<f(x_0)+\varepsilon\}$ and $\{x\in M : f(x)>f(x_0)-\varepsilon\}$. Since $f$ lower and upper semicontinuous, both these sets are open. Then, since $x_0\in\{x\in M : f(x)<f(x_0)+\varepsilon\}$, there is $r_1>0$ such that $B(x_0,r_1)\subset \{x\in M : f(x)<f(x_0)+\varepsilon\}$ and analogously we get $r_2>0$ such that  $B(x_0,r_2)\subset \{x\in M : f(x)>f(x_0)-\varepsilon\}$. Pick $\delta=\min\{r_1,r_2\}$, so $B(x_0,r)$ is contained in both those sets and consequently
$$
d(x_0,x)<\delta\Rightarrow |f(x)-f(x_0)|<\varepsilon.
$$
Since this happens for any $x_0\in M$ and $\varepsilon>0$,    $f$ is continuous.
