尝试使用Except String vs Int Python

时间:2015-12-01 20:32:22

标签: python int type-conversion

我不确定是使用try / except还是if条件来检测数字是int还是float。我知道我的输入是一个浮点数或一个int,我想为所有浮点数引发一个值错误,如果数字为int则执行某些操作。可以看到这种行为的一个例子是一个因子...但是,我不希望将5.0转换为5.什么是最好的方法?

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

我读了这个问题Parse String to Float or Int,但我仍然感到困惑

2 个答案:

答案 0 :(得分:4)

此解决方案依赖于int("1.235")将引发值错误的事实,因为要转换它的字符串必须 literal int 。这需要my_value为字符串!因为int(1.235)只会将float截断为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"

答案 1 :(得分:1)

如果你想类型安全地检查变量是否是int,你可以使用isinstance()

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

这显然也会为任何字符串提升ValueError(因此"5"不起作用,如果这是你想要的话。)

相关问题