I'm getting strange output and am trying to track down what might be
causing it. I have the following code in my .nb file:
(* begin code *)
Test[ ] := Module[ {i, thesum},
thesum = 0;
For[ i = 1, i <= 3, i++,
thesum = thesum + i
]
Return[ thesum ]
]
Test[ ]
(* end code *)
The output I would expect would be simply
6
But, I get
Null Return[6]
Alternatively, if I change the last line of the Test function to be
thesum
instead of
Return[ thesum ]
I get
6 Null
as the output. If I remove the for loop, I get expected behavior,
i.e.,
Test[ ] := Module[ {i, thesum},
thesum = 1 + 2 + 3;
(*
For[ i = 1, i <= 3, i++,
thesum = thesum + i
]
*)
Return[ thesum ]
]
yields the output
6
as one might expect. I'm not sure what this all means, or what it is
complaining about. I have other for-loops that are apparently working
properly. So, can anyone give me an idea what might be going wrong
here?
Thanks.
Dave
You forgot a semicolon. The newline after For[] was interpreted as
multiplication. The correct version is
test[ ] := Module[ {i, thesum},
thesum = 0;
For[ i = 1, i <= 3, i++,
thesum = thesum + i
]; (* <--- note the semicolon *)
Return[ thesum ]
]
try
Test[] := Module[{i, thesum}, thesum = 0;
For[i = 1, i <= 3, i++, thesum = thesum + i]; (* <= Here *)
Return[thesum]]
For[] return Null and since you have forgotten the CompoundExpression[] ";"
the result is interpreted as a product For[__]*Return[_]
and since Return[] does not work in expressions, you
get Null*Return[6]
Regards
Jens
You are missing a semi-colon. Try this:
Test[] := Module[{i, thesum},
thesum = 0;
For[i = 1, i <= 3, i++, thesum = thesum + i];
Return[thesum]]
--
Helen Read
University of Vermont
Test[] := Module[{i, thesum}, thesum = 0;
For[i = 1, i <= 3, i++, thesum = thesum + i] ;
Return[thesum]]
Test[]