# Why function cannot be defined inside For loop? [closed]

I have a following code (which is simplified version of what I am doing):

For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2
Print[{i, f[i]}]
]


And the question is simple: why such thing doesn't work at all. It does not write any output, nor it prints anything, nor it displays any error. Just nothing.

• Why put the function definition inside the loop, even? Take it out of the loop; you save some effort that way. – J. M. is in limbo Apr 26 '13 at 11:50
• You should have mentioned in your question that your function is changing. But also in this case, you should try to define it outside of your for loop (or Table). E.g. you could work with a Piecewise function. But it is difficult to give more exact hints without knowing the problem better. Btw: You do not get an error message, because your code is not really wrong (the syntax is correct – but not the logic). Run it and check the result of f, then you see that your code worked – just in a way you do not want it to work. – partial81 Apr 26 '13 at 12:07
• The solution goven by partial81 is just fine. – Misery Apr 26 '13 at 12:08
• Why was this closed? Because it was just a programming error? I have seen other examples of this in questions that are not closed. The "too localized" doesn't feel right to me. Also the rage about using a loop seems unnecessary to me. Reminds me of when people use capital letters for symbols/function names. True, but needless comments. – Gabriel Apr 26 '13 at 17:28
• @Gabriel: for i in range(1,10): def ABC(y): print(y) ABC(i) Of course I can. Just get the indent right. – Misery Apr 26 '13 at 18:10

I think you only forgot a comma. Try:

For[i = 1, i <= 5, i++, {f[x_] := Sin[x]^2, Print[{i, f[i]}]}]


If I were you, I would not define a function in a For Loop (can be time consuming). And, if possible, I would work with a Table because this works faster too. So do something like:

f[x_] := Sin[x]^2;
Table[{i, f[i]}, {i, 1, 5}]

• Why a list rather than a CompoundExpression (;)? Now you make it look even more like its another language ;). – Jacob Akkerboom Apr 26 '13 at 11:58

It is of course possible to redefine functions within loops in Mathematica. You are actually just missing a semicolon at the right place for your code to work as intendend:

For[i = 1, i <= 5, i++,
f[x_] := Sin[x]^2;
Print[{i, f[i]}]
]


It's probably worth noting (as Jacob did in his comment) that the semicolon is just a shortcut for a CompoundExpresson, so something like a;b;c looks like this in FullForm: CompoundExpression[a,b,c], which you can check with e.g. FullForm[Hold[a;b;c]]. As the default evaluation order is to evaluate arguments from left to right, you could actually use any other symbol without (matching) definitions and Hold attributes instead of CompoundExpression, which is why e.g. List in the other answer also works, but of course using CompoundExpression is much more standard and clear. The main difference is that CompoundExpression returns the return value of its last argument, which other symbols won't do, the following might make these subtleties more clear:

Print[a];Print[b];c
CompoundExpression[Print[a],Print[b],c]
{Print[a],Print[b],c}
List[Print[a],Print[b],c]
somethingelse[Print[a],Print[b],c]


Without that semicolon (CompoundExpression) what you do is to redefine f[x_] to Sin[x]^2*Print[{i,f[i]}] in every loop pass without ever using that function. This is also the reason why you don't see any output. As it is perfect valid code there is no reason to expect any error or even warning messages - Mathematica can't (yet) guess that this is not what you intended...

You'll often find that people tell you to not use loops in Mathematica, but I think there are many cases where using loops is the right thing to do. You'll find that other constructs will give you better performance, less typing and still clearer code in many cases, though. Learning those other possibilities will be of great advantage if you plan to use Mathematica more often in the future. For reasons mentioned e.g. in answers to this question I'd strongly suggest to avoid For loops, though. Here is the same thing using a Do loop:

Do[
f[x_] := Sin[x]^2;
Print[{i, f[i]}],
{i,5}
]


You should also learn about the difference of Printing a result and returning it. In almost all cases you want to return what you calculate and not just print it, and thus you'd probably rather use something like this:

Table[
f[x_] := Sin[x]^2;
{i, f[i]},
{i,5}
]

• Albert, this question has been closed and already has two delete votes against it. Would you consider either editing this question to to make specific room for this answer, or even posting a new self-Q&A to share this information? The votes clearly indicate that the community values this answer, but at present this is not a good place for it. – Mr.Wizard Aug 6 '16 at 10:18
• @Mr.Wizard: hm, I would do that but honestly have no idea about what I could ask to give this answer. It just explains why the code of the OP didn't work, and it was his question why the code didn't work. The combination of errors and misunderstandings in his snippet seems to be quite unique :-) Any suggestions? – Albert Retey Aug 7 '16 at 17:34