I’m trying to get a number as CLI input from python. Valid input should be either an int or a float and I need to maintain type. So validating an int and returning a float wouldn’t work.
This is the best thing I’ve been able to come up with and it’s not all that good.
def is_valid(n):
try:
if '.' in n: return float(n)
return int(n)
except ValueError:
print "try again"
def num_input(s):
n = raw_input(s)
while is_valid(n) is None:
n = raw_input(s)
return is_valid(n)
valid_num = num_input("Enter a valid number: ")
Clearly this isn’t the best way.
After considering the early answers and thinking about it a bit more the solution I came up with is:
I really want an input function not just a validation function; however, I think HYRY‘s suggestion to loop over int, float, complex is a good one. I took win‘s suggestion to use recursion instead of looping, understanding that a really confused and persistent user could exceed the max recursion depth. Although I don’t need it now, I think Karl Knechtel is correct in making the error an arg instead of hard coded.