Re: strange behavior
- To: mathgroup at smc.vnet.net
- Subject: [mg104823] Re: strange behavior
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Wed, 11 Nov 2009 04:25:40 -0500 (EST)
- References: <hdbgva$j3v$1@smc.vnet.net>
Jason Winters wrote: > Hi! I am wondering why these two modules behave differently > > > Module[{ans = ""}, > For[i = 1, i < 10, i++, > ans = InputString["Enter a String"]; > Print[ans] > ] > ] > > > and > > > Module[{ans = ""}, > For[i = 1, i < 10, i++, > ans = InputString["Enter a String"] > Print[ans] > ] > ] > > > One prints out a bunch of extraneous Null's > > Also is there anyway to type variable in Mathematica i.e. declare i to be and > integer or string or whatever. > > > Thanks for any help you can give. > Sorry for the simpleness of these questions. > > Thanks > > A very good way to explore what is going on here, is to wrap Hold around the module to stop it being evaluated, and FullForm, to study the structure of the code: FullForm[Hold[Module[{ans = ""}, For[i = 1, i < 10, i++, ans = InputString["Enter a String"] Print[ans] ] ] ]] Doing this, you will see that because of the missing semicolon, the assignment RHS gets multiplied by the Print - generating a mess involving Null's. I would terminate every statement in the body of a For loop (including the Print) unless you specifically want the return value. There is a subtlty here that is worth mentioning in this context. Statements separated by a newline (but without a semicolon) are treated as multiplications, EXCEPT if they appear at the top level of a cell (not the case here) - in which case they are treated as two separate executable statements! David Bailey http://www.dbaileyconsultancy.co.uk