Off[General::spell1];
Clear[Lagrange,XY0,t];
Lagrange[XY0_,t_] := 
Block[{j,k,n,prod,sum,term,X,Y,XY},
  XY = XY0;
  n = Length[XY]-1;
  X = Transpose[XY][[1]];
  Y = Transpose[XY][[2]];
  sum = 0;
  Clear[P,L];
    For[k=0,k<=n,k++,
      prod = 1;
      For[j=0,j<=n,j++,
        term=Which[j==k,1, j!=k,
    (t-X[[j+1]])/(X[[k+1]]-X[[j+1]])];
        prod=prod term ];
      L[k,x_] = prod;
      sum = sum + Y[[k+1]] prod ];
  P[x_] = sum;
  Return[P[x]]; ];
On[General::spell1];

Clear[XY];
XY={{0,1}, {0.5, 2}, {1,0}, {1.5, -1}, {2, 1}}

Clear[P1,x];
P1[x_] = N[Lagrange[XY,x],10]

Q1[x_] = N[Expand[P1[x]],10]

dots = ListPlot[XY,PlotStyle->{PointSize[0.02]},
        DisplayFunction->Identity];
 gr1 = Plot[{ Q1[x]},{x,-0.5, 2.5},
DisplayFunction->Identity];
Show[gr1,dots,PlotRange->{{-0.5,2.5},{-4,4}},
AxesLabel->{"x","y"},
PlotLabel->"f(x) and the Lagrange polynomial.",
DisplayFunction->$DisplayFunction];

Clear[f,x];
f[x_] = Cos[x]
XY = {{0.0,f[0.0]},{0.6,f[0.6]},{1.2,f[1.2]}};
N[XY,10]

Clear[P2,x];
P2[x_] = N[Lagrange[XY,x],10]

Q2[x_] = N[Expand[P2[x]],10]

dots = ListPlot[XY,PlotStyle->{PointSize[0.02]},
        DisplayFunction->Identity];
Print["The function is f[x] = ",f[x]];
gr2 = Plot[ Cos[x], {x,-1,2}, 
     DisplayFunction->Identity];
gr3 = Plot[Q2[x] ,{x,-1,2.1},
PlotStyle -> Thickness[0.01],
DisplayFunction->Identity];
Show[gr2,gr3,dots,PlotRange->{{-1,2.1},
{-0.8,1.15}},
AxesLabel->{"x","y"},
PlotLabel->"f(x) and the Lagrange polynomial.",
DisplayFunction->$DisplayFunction];

Clear[f,x];
f[x_] = Cos[x]
XY = {{0.0,f[0.0]},{0.4,f[0.4]},
{0.8,f[0.8]},{1.2,f[1.2]}};N[XY,10]

Clear[P3,x];
P3[x_] = N[Lagrange[XY,x],10]

Q3[x_] = N[Expand[P3[x]],10]

dots = ListPlot[XY,PlotStyle->{PointSize[0.02]},
        DisplayFunction->Identity];
Print["The function is f[x] = ",f[x]];
gr4 = Plot[Q3[x] ,{x,-1,2.1},
PlotStyle -> Thickness[0.01],
DisplayFunction->Identity];
Show[gr2,gr4,dots,PlotRange->{{-1,2.1},
{-0.8,1.15}},
AxesLabel->{"x","y"},
PlotLabel->"f(x) and the Lagrange polynomial.",
DisplayFunction->$DisplayFunction];