# 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.

-

## closed as too localized by Sjoerd C. de Vries, Leonid Shifrin, belisarius, Ajasja, Oleksandr R.Apr 26 '13 at 13:10

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

Why put the function definition inside the loop, even? Take it out of the loop; you save some effort that way. –  Ｊ. Ｍ. Apr 26 '13 at 11:50
@J.M.: because I have reason for putting it inside. In fact the function is a bit different everytime. And I can do such thing in Scilab, Python or in C++. –  Misery Apr 26 '13 at 11:54
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[1], 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
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}
]

-