Let $(X,d)$ be a metric space. Show that if for every continuous function $f: X \to \mathbb{R}$ such that $f(X)$ is an interval holds, then $X$ is connected.
My attempt is to show otherwise. Suppose that $X$ is not connected. So we can find two disjoint open sets $U$ and $V$ such that $X=U\cup V$. Now I want to define a continuous function $f$ for which $f(X)$ would not be an interval. We know that the metric $d$ is a real-valued continuous function on $X \times X$. So my guess is we could build the desired function $f$ out of this metric. But I don't know how to do this.
If $X$ is not connected, and if $U,V$ are as in your attempt, define $f_1:U\to \mathbb R: u\mapsto 0$ and $f_2:V\to \mathbb R: v\mapsto 1$. Then, the pasting lemma shows that $g=f_1\cup f_2:X\to \mathbb R$ is continuous but $g(X)$ is not an interval.