Prove $X$ (Metric Space) is connected $\iff$ for every continuous $f:X\rightarrow \mathbb R$, $f(X)$ is connected and $ \subset \mathbb R$
I'd appreciate if somebody posted a whole answer, so that I can work through it.
I tried proving by contradiction. Assume $X$ is connected but $f(X)$ is not. Then we can find open sets $U,V$ that partition $f(X)$ and their intersection is empty.
Then $f^{-1}(U)\cap(X)\subset X$ and $f^{-1}(V)\cap(X)\subset X$. Since $U\cap V$ is empty we also get that $f^{-1}(U)\cap f^{-1}(V)$ is empty. Thus they $f^{-1}(U)\cap(X)$ and $f^{-1}(V)\cap(X)$ partition $X$ which is a contradiction?
This proof would work for $f:X\rightarrow Y$ where $Y$ is another metric space, but does it also work for $\mathbb R$?