[Tutor] Recursive user input collection problem

William Witteman yam at nerd.cx
Tue Oct 13 22:22:15 CEST 2009


I need to collect a couple of integers from a user, but I want to make
sure that I actually get integers.  I tried this, but subsequent calls
to the function don't update variable.  I'm not sure this is terribly
clear - here's the code:

num_of_articles = 0
num_of_reviewers = 0

def getinput(variable,prompt):
  """
  Get the input by prompting the user and collecting the response - if it is 
  a non-integer, try again.
  """
  variable = 0
  variable = raw_input(prompt)

  try:
    int(variable)
    return variable

  except ValueError:
    print("We need an integer (number) here.")
    getinput(variable,prompt)


num_of_articles = getinput(num_of_articles,"Enter number of articles: ")
num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ")

print(num_of_articles)
print(num_of_reviewers)


This works fine if I put in good input, but not if I pass in a bad
value.  Can anyone show me where I have gone astray?  Thanks.
-- 

yours,

William



More information about the Tutor mailing list