TITLE: $X$ compact metric space, $f:X\rightarrow\mathbb{R}$ continuous attains max/min
QUESTION [14 upvotes]: Let $X$ be a compact metric space, show that a continuous function $f:X\rightarrow\mathbb{R}$ attains a maximum and a minimum value on $X$.   

Attempt: So the important thing is that I have previously shown that such a function is bounded and that for compact $X$, $f(X)$ is compact given $f$ continuous. In $\mathbb{R}$, compact $\implies$ closed and bounded. So $f(X)$ is closed and contains its accumulation points, and it is bounded so $\exists \sup(A),\inf(A)$ and since closed $\implies \sup(A)\in A, \inf(A)\in A$. 
Did I miss anything/make an unwarranted leap of logic?

REPLY [5 votes]: Your argument is fundamentally sound, but you have to assume that your metric space is nonempty. Here is a direct proof that requires no other results (the proof generalizes, like yours, to arbitrary topological spaces):
Let $X$ be a nonempty metric space and $f:X\to\mathbb{R}$ a continuous function without a maximum. Then $X$ has an open cover without a finite subcover. 
Proof: 

Suppose $f(X)$ is unbounded. Then $\big\{f^{-1}\big((-\infty, n)\big):n\in\mathbb{N}\big\}$ is an open cover without finite subcover. 
Suppose $f(X)$ is bounded, with supremum $s$. Since $f$ has no maximum, $s\notin f(X)$ and $\big\{f^{-1}\big((-\infty, s-1/n)\big):n\in\mathbb{N}\big\}$ is an open cover without finite subcover.