如何检查raw_input是否为float并且只包含一个小数点?

时间:2014-06-22 08:36:30

标签: python python-2.7 types raw-input

代码:

x=raw_input("Enter: ")
if x.isfloat():
   print x
else:
   print "error"

错误:

Traceback (most recent call last):
  File "C:/Python27/DLLs/delete", line 4, in <module>
    if not x.isNumber():
AttributeError: 'str' object has no attribute 'isNumber'

1 个答案:

答案 0 :(得分:4)

为什么不使用try并查找?

x = raw_input("Enter: ")
try:
    x = float(x)
except ValueError:
    print "error"
else:
    print x

这种"easier to ask for forgiveness than permission"样式是一种常见的Python习语。


如果你意味着检查小数点后只有一位数的数字,你可以稍微调整一下:

try:
    if len(x.split(".", 1)[1]) == 1:
        x = float(x)
    else:
        print "error" # too many d.p.
except (IndexError, ValueError):
    print "error" # no '.' or not a float
else:
    print x

此处IndexError会抓住x不包含任何'.'ValueError捕获x无法解释为float。一般情况下,您可能希望将这些检查分开,以向用户报告更有用的错误(例如"Error: couldn't convert '{0}' to float.".format(x)),甚至提出实际的Exception

相关问题