Recursive function for integer number input

Asked

Viewed 237 times

6

I have this code but it doesn’t work very well, I mean, if it’s whole at first numOfValues is correct, but if it is not gets the type None, for what remains in memory is the first input (which is not integer). I would like that, regardless of the attempts I make, the numOfValues always had the value of the last input, and the function stopped when inserting 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
...

1 answer

3


I believe only one should be missing return when caught the exception.

return return_int()

Thus remaining the code:

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

Exit:

$ 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
$
  • 1

    Believe me very well. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.