[Tutor] Recursive user input collection problem

William Witteman yam at nerd.cx
Thu Oct 15 15:07:14 CEST 2009


On Thu, Oct 15, 2009 at 07:54:23AM -0400, Dave Angel wrote:
>William Witteman wrote:
>>Thanks to all who responded.  There were several good points about the
>>code itself, all of which both helped and work.
>>
>>I will likely use Alan's example because I find it the most lucid, but
>>the other suggestions are good signposts to other ways to do the same
>>thing (but right, as opposed to how I was doing it).
>>
>>Lie's suggestion that I didn't understand the calling structure of
>>Python was right on the money, and his included link helps with that,
>>too.  Thanks again.

>You need a loop, and putting a while True:  around the whole thing
>solves it nicely.  Don't *call* the function again, just loop back
>and do the operation again.  That's what loops are for.

True, that's why my code currently looks like this:

def getinput(prompt):
  """  
  Get the input by prompting the user and collecting the response - if it is 
  a non-integer, try again.
  """  
  while True:
    try:
      return int(raw_input(prompt))
    except ValueError:
      print("We need an integer (number) here.")                                

>Incidentally, learning about recursion is a very good thing, and
>useful.  I just don't think it's the right answer here.

I wasn't learning about recursion - I have to use it fairly often, but
you are right that it isn't the right approach here.
-- 

yours,

William



More information about the Tutor mailing list