0

I am not sure whether to use try/except or an if condition to detect whether a number is an int or a float. I know my input is either a float or an int, and I want to raise a value error for all floats, and do something if the number is an int. An example of where this type of behavior might be seen is a factorial... However, I don't want a 5.0 to be converted to a 5. What is the best approach?

factorial(5)
> 120
factorial(asdf)
> ValueError
factorial(5.0)
> ValueError

I read this question Parse String to Float or Int but I am still confused

Community
  • 1
  • 1
qwertylpc
  • 2,016
  • 7
  • 24
  • 34
  • 2
    I would suggest that you don't detect type of input at all. If you simply implement your `factorial` not caring about type of input, it will probably (a) work for types which make sense, and (b) raise an execption for other types anyway. – zvone Dec 01 '15 at 20:40
  • What `factorial` function are you talking about? Is it one you've written? – tdelaney Dec 01 '15 at 20:43
  • 1
    @tdelaney Im pretty sure its just `math.factorial` but a good question all the same – Joran Beasley Dec 01 '15 at 20:45
  • I don't think it matters. I am just using a factorial as an example where I want to draw the distinction between floats and ints. The actual use is for analyzing English Soccer data that I scraped without an API so it is a bit messy. I could do it another way, but since I had the thought and didn't know the solution I figured I would ask. The question is more theoretical... – qwertylpc Dec 01 '15 at 20:48
  • @qwertylpc Your question is confusing. If you are talking about type checking and raising exceptions, how about a small example that does that? Your `factorial` example doesn't seem to have much to do with anything. – tdelaney Dec 01 '15 at 20:57
  • 1
    @JoranBeasley `math.factorial` doesn't raise a ValueError with `5.0`. I was hoping to prod OP into an example that has something to do with his problem. – tdelaney Dec 01 '15 at 21:00
  • The only way you can use try/except is if you attempt some operation that requires a float and raises an exception on fail. `isinstance` makes more sense. You link to a question about strings... could this thing you want to check be a string that you plan to convert to an int? If so `'.' in asdf` would be a good check. – tdelaney Dec 01 '15 at 21:12

2 Answers2

4

this solution counts on the fact that int("1.235") will raise a value error as for a string to convert it must be a literal int. This requires my_value to be a string! as int(1.235) will simply truncate the float to an int

my_value = raw_input("Enter Value")

try:
  my_value = int(my_value)
except ValueError:
  try:
     float(my_value)
     print "Its a float not an int!"
     raise ValueError("Expected Int, got Float!")
  except ValueError:
     print "Its a string not a float or int"
     raise TypeError("Expected Int, got String!")
else:
  print "OK its an int"
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

If you want to typesafely check if the variable is an int, you can use isinstance():

def factorial(var):
    if not isinstance(var, int):
        raise ValueError('var must be an int')
    # do stuff

This would also raise a ValueError for any string obviously (so "5" wouldn't work, if that's what you want).

Felk
  • 7,720
  • 2
  • 35
  • 65
  • 1
    I think this is a resonable solution since it advises `isinstance` (which is so much better than `type(x)` ) ... so +1 ... but I dont think this will quite solve the problem the OP has (all the same +1 for `isinstance`) – Joran Beasley Dec 01 '15 at 20:44