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

7
  • 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. Commented Dec 1, 2015 at 20:40
  • What factorial function are you talking about? Is it one you've written? Commented Dec 1, 2015 at 20:43
  • 1
    @tdelaney Im pretty sure its just math.factorial but a good question all the same Commented Dec 1, 2015 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... Commented Dec 1, 2015 at 20:48
  • 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. Commented Dec 1, 2015 at 21:00

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

7 Comments

You should remove the raise otherwise it still raises an error
I assumed he would want to catch it else where if that is not the case then yes the raise should be removed
Note that, like in your example, it must be ensured that my_value is originally a string. Otherwise this would still pass floats.
raw_input is guaranteed to return a string ... but yes duly noted
@JoranBeasley if OP just wants a valueError raised if not an int then you don't need the second try except statement
|
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).

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.