> 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
When the exception is thrown the "return variable" line is not executed. The path jumps down to the except block and runs that. Thus when you are unrolling the recursion the first getinput() does not return a value. A finally block after the exception block will execute whether or not the exception is thrown after the other code runs. You also need to assign the return value of getinput() within your except block. Finally there is no need to pass variable into the function as you immediately change it to zero. Chris
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor