简体   繁体   中英

Try Except String vs Int Python

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

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"

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM