2

In Python, I often use local variables in defining functions, like so:

def f(x):
   k = initialk
   < 'do something to k' >
   return(k)

I would like to do something similar in Mathematica for instance, I would want:

f[x_]:=
For[i=0;k=x,i<x,i++,k=k^2+1];
Return[k] 

to return $(\cdots((x^2+1)^2+1)^2+\cdots1)^2$.

How does one ordinarily do this in Mathematica?

R. Burton
  • 145
  • 4

1 Answers1

10

If you want, you could write some thing like this

f[x_] := Module[{k = x},
  Do[k = k^2 + 1, {i, 0, x - 1}];
  k]

A more natural form would be

f[x_] := Nest[#^2 + 1 &, x, x]
mikado
  • 16,741
  • 2
  • 20
  • 54