1

I had something along the lines of:

Func1[x_]:=(For[i=1,i<somenum,i++,
        Func2 [ x[[i]] ]
];)

Func2[a_]:=(For[i=1,i<anothernum,i++,
               Print[ToString[i]] ];)

And found that the i from the loop in Func1[] was being incremented by the loop in Func2[]. This was really surprising to me: I assumed, being local variables for defined at different points in the stack, they wouldn't know about each other. Changing the i in Func1[] to k fixed everything.

Is this usual/normal?

YungHummmma
  • 3,042
  • 15
  • 30
  • i is not local variables.The color of i is blue,which means global variables.Maybe you need learn about Module. – Apple Jul 10 '14 at 15:02

1 Answers1

3

Because i here is a global variable. This is one of the reasons why I always suggest to beginners never to use For loops.

If you translate procedural code from other languages, use Do instead.

There are very few cases in Mathematica when For is the best solution. When you get more experienced, you'll be able to make that decision. Until then it is really the best approach to pretend that For doesn't exist in Mathematica.


You can use Module to localize variables.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • Ah... is it because in a For[], I'm defining i when do i=1, but in a Do[], it's local because it's all in the {i,imin,imax}? Thanks! – YungHummmma Jul 10 '14 at 15:08
  • @YungHummmma You can always localize i explicitly using Module. But that's more complicated than just using Do, which does auto-localize. Also, Do is more readable (because it's much shorter, and doesn't force one to look for commas and semicolons). Once you're using do, it's often just one step to switch to Table instead and get rid of the procedural code for good. – Szabolcs Jul 10 '14 at 15:10
  • Hm, Do[something[i],{i,i1,i2}] indeed looks much cleaner than Module[{i},For[i=i1,i<=i2,++i, something[i]]]. – Ruslan Oct 25 '16 at 11:46