MathGroup Archive 2011

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

Search the Archive

Re: Local Variables in Do[]

  • To: mathgroup at
  • Subject: [mg116853] Re: Local Variables in Do[]
  • From: Bill Rowe <readnews at>
  • Date: Wed, 2 Mar 2011 04:35:58 -0500 (EST)

On 3/1/11 at 5:23 AM, ashai at (adamimos) wrote:

>I hate to have such a newbie question, but I'm new to programming in
>Mathematica. I have nested loops, and I'd like to change a global
>variable inside of the loop. It seems that Mathematica makes all
>variables defined inside of Do functions local, is this true?

No, as is easily demonstrated by:

In[1]:= x = 4;
Do[x += n, {n, 10}];

Out[3]= 59

In[4]:= 59 - Sum[n, {n, 10}]

Out[4]= 4

As you can see from the above, the value of x, a global
variable, was modified and retains that modification outside the
Do loop. Also, note if you paste the code into a fresh session
notice the syntax coloring for x and n is different. n will get
colored as a local variable, x will be colored blue like any
global variable with no assigned value. Once the code runs, the
color of x will change to black due to the assignment but the
color of n will remain unchanged.

  • Prev by Date: Re: making something autoexecute before normal execution
  • Next by Date: Re: Prepending Data to a File
  • Previous by thread: Re: Local Variables in Do[]
  • Next by thread: Sorting a list of symbols