MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: local variables - Module, For loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113034] Re: local variables - Module, For loop
  • From: "Nasser M. Abbasi" <nma at 12000.org>
  • Date: Tue, 12 Oct 2010 04:22:53 -0400 (EDT)
  • References: <i8ukij$o9s$1@smc.vnet.net>
  • Reply-to: nma at 12000.org

On 10/11/2010 2:14 AM, Sebastian Schmitt 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?
>

Yes, a better way is to use functions or blocks if you want local scope 
of variables.

A symbol in global. If you want to be local, make it so. (You do that in 
C++ also?)


You allready made a module, why not simply add 'i' as local variable there?

Instead of

Module[{},For[i=0,i!=x,i++,Print[i]]]

write

f[x_]:=Module[{i},For[i=0,i!=x,i++,Print[i]]]

In[90]:= f[2]
During evaluation of In[90]:= 0
During evaluation of In[90]:= 1

In[91]:= i
Out[91]= i

--Nasser


  • Prev by Date: Why I keep getting error exporting notebooks to HTML? Crashes Mathematica,
  • Next by Date: Re: local variables - Module, For loop
  • Previous by thread: Re: local variables - Module, For loop
  • Next by thread: Re: local variables - Module, For loop