Re: local variables - Module, For loop

*To*: mathgroup at smc.vnet.net*Subject*: [mg113056] Re: local variables - Module, For loop*From*: "Ingolf Dahl" <ingolf.dahl at telia.com>*Date*: Tue, 12 Oct 2010 04:27:06 -0400 (EDT)

Sebastian, If you look in the Help for For, you might read "For[start,test,incr,body] executes start, then repeatedly evaluates body and incr until test fails to give True." Thus For handles very general types of loops and conditions, and if you want to use it for iteration of integer variables, that is your own choice, and Mathematica does not know that beforehand. Thus For does not know which variables to consider as locals. However, a better choice in this case is the Do command, and with f[x_] := Do[Print[i], {i, 0, x - 1}] the variable i is considered as local (internally localized by a Block command). You might also consider the While command, but that also is general, and does not localize the variables. If I get it right start; While[test, body; incr] should behave exactly as the For[start,test,incr,body] command. The For command is thus superfluous, present in Mathematica to satisfy old Fortran programmers, in the same way as the Goto command is there for old Basic programmers. Best regards Ingolf Dahl > -----Original Message----- > From: Sebastian Schmitt [mailto:sschmitt at physi.uni-heidelberg.de] > Sent: den 11 oktober 2010 11:15 > To: mathgroup at smc.vnet.net > Subject: [mg113011] local variables - Module, For loop > > Dear all! > > (I recycle my disclaimer.) > > I'm new to Mathematica with a background mostly in C++. Many times I > have the impression that my style is not natural-Mathematica > (Mathematicaesque so to say). > > If I have a For loop in a function like this: > > In[39]:= f[x_] := Module[{}, > For[i = 0, i != x, i++, > Print[i] > ] > ] > > In[41]:= f[2] > > During evaluation of In[41]:= 0 > > During evaluation of In[41]:= 1 > > In[42]:= i > > Out[42]= 2 > > I was surprised to find "i" being not local to the For loop. Do I have > to keep track of all my throw-away-variables and put them in the list of > local variables of the Module? I find it pretty tedious. Is there a > better way? > > Thanks in advance, > > Sebastian