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

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

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


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

How does one ordinarily do this in Mathematica?

  • 1
    $\begingroup$ Module, With, or Block will do what you're looking for. $\endgroup$ – Carl Lange Mar 8 '20 at 18:23
  • $\begingroup$ Don’t try to program in Mathematica by reproducing Python practices. You will write inefficient code and end up very frustrated. $\endgroup$ – MarcoB Mar 9 '20 at 2:47
  • 1
    $\begingroup$ @MarcoB Is there a "Good Coding Practices for Mathematica" somewhere that I could refer to? $\endgroup$ – R. Burton Mar 9 '20 at 19:25
  • $\begingroup$ @R.Burton if you asked that as a question, I think you would get some pointers to suitable material. $\endgroup$ – mikado Mar 9 '20 at 21:18
  • $\begingroup$ @R.Burton For a start, see Where can I find examples of good Mathematica programming practice? $\endgroup$ – MarcoB Mar 9 '20 at 22:16

If you want, you could write some thing like this

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

A more natural form would be

f[x_] := Nest[#^2 + 1 &, x, x]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.