2
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ Module, With, or Block will do what you're looking for. $\endgroup$ – Carl Lange Mar 8 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 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 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 at 21:18
  • $\begingroup$ @R.Burton For a start, see Where can I find examples of good Mathematica programming practice? $\endgroup$ – MarcoB Mar 9 at 22:16
10
$\begingroup$

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]
| improve this answer | |
$\endgroup$

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.