[Tutor] Recursive user input collection problem
Dave Angel
davea at ieee.org
Tue Oct 13 23:02:32 CEST 2009
William Witteman wrote:
> 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.
>
You called getinput() from inside getinput(), which is a recursive
call. So what happens is whenever the user makes a mistake, you have
two copies of the function running. And they get their own copies of
variables, which isn't what you want in this case. What you want
instead is to loop back to the beginning, not to call.
In this simple case, you can simply enclose the entire function in a
while True:
loop. And when the exception happens, you loop around back to the
beginning.
DaveA
More information about the Tutor
mailing list