Recursive function for integer input

6

I have this code but it does not work very well, that is, if it is integer at first numOfValues is correct, but if not it is with type None , since what is in memory is the first input ( which is not integer). I would like, regardless of the attempts you make, numOfValues would always have the value of the last input, and the function would stop when you entered an integer, so it would be numOfValues = INT (when the function returns x )

def return_int():
  x = raw_input("Number of names to insert?\n")
  try: 
    int(x)
    return int(x)
  except ValueError:
    print "must be an integer"
    return_int()

numOfValues = return_int()
print numOfValues
...
    
asked by anonymous 04.03.2015 / 15:56

1 answer

3

I believe that only a return should be missing when the exception is caught.

return return_int()

Getting the code like this:

def return_int():
    try:
        x = int(raw_input("Number of names to insert?\n"))   
        return x
    except ValueError:
        print "must be an integer"
        return return_int()

numOfValues = return_int()
print numOfValues

Output:

$ python foo.py
Number of names to insert?
1
1
$ python foo.py
Number of names to insert?
ZZZZZZ
must be an integer
Number of names to insert?
2
2
$
    
04.03.2015 / 16:50