Show that if every continuous function $X \rightarrow \mathbb{Z}$ is constant then X is connected

Show that a nonempty metric space $X$ is connected if and only if every continuous function $X\rightarrow \mathbb{Z}$ is constant.

I have a difficult time proving the direction that

every continuous function $X \rightarrow \mathbb{Z}$ is constant $\Rightarrow$ $X$ is a nonempty connected metric space

Any help would be appreciated, thank you.

• How about: suppose $X$ is disconnected, then show you can construct a continuous functions $f: X \rightarrow \mathbb{Z}$ that is not constant? – user98404 Nov 22 '16 at 6:06
• @chell I see. I can suppose $X$ is disconnected, then there exists two open sets $A$ and $B$ that partitions $X$, then I construct the mapping $f$ such that $A$ maps to a constant, $B$ maps to another constant. All it remains is to show that $f$ is continuous. Is this correct? – Huiwen Zheng Nov 22 '16 at 6:16
• Yes you are correct @HuiwenZheng;Just show $f$ is continuous – Learnmore Nov 22 '16 at 8:48

Let $A$ and $B$ open subsets of $X$ such that

$A \cap B= \emptyset$ and $A \cup B= X$ .

Define $f:X \to X$ by

$f(x)=\begin{cases} 1 & \text{$x\in A$}\\ 0 & \text{$x\in B$} \end{cases}$

To get a contradiction, show that $f$ is continuous.