Polynomial function on algebraic sets Given two disjoint algebraic sets $X_1$ and $X_2$ over a field $K$. Is it always possible to find a polynomial function such that $f$ constantly takes 0 on $X_1$ and constantly takes 1 on $X_2$?

Yes. Suppose they live in $\mathbb{A}^n_K$. Let $R = K[x_1,\dots,x_n]$. Let $I(X_1) = (f_1,\dots,f_k)$ and $I(X_2) = (g_1,\dots,g_\ell)$. Let $X = X_1\cup X_2$. Let $I = I(X) = I(X_1)\cap I(X_2)$. $X$ is an algebraic set covered by the distinguished open sets $D(f_i)$, $1\le i \le k$, and $D(g_j)$, $1\le j \le \ell$. Moreover, $D(f_i)\cap D(g_j) = \emptyset$ for each $(i,j)$, since $X_1\cap X_2 = \emptyset$. So there is a regular function $\bar h \in R/I$ on $X$ with $\bar h(X_1) = 0$ and $\bar h(X_2) = 1$ (see Proposition 3.10 of these notes). Then lift $\bar h$ to $h\in R$.
This is a consequence of the sheaf-iness of regular functions on algebraic sets.
