Re: local variables - Module, For loop
- To: mathgroup at smc.vnet.net
- Subject: [mg113043] Re: local variables - Module, For loop
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Tue, 12 Oct 2010 04:24:36 -0400 (EDT)
f[x_] := Module[{i}, For[i = 0, i != x, i++, Print[i]]] f[5] Don't use a For loop and you won't need the "throw-away-variable" f[x_] := Print /@ Range[0, x - 1] f[5]; Print is often unnecessary. If you want to display the results in a column, use Column f[x_] := Range[0, x - 1] f[5] // Column Bob Hanlon ---- Sebastian Schmitt <sschmitt at physi.uni-heidelberg.de> wrote: ============= 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