Search code examples
pythonpython-2.7typesraw-input

How to check if raw_input is float and contains only one decimal point?


Code:

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

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'

Solution

  • Why not just use try and find out?

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

    This "easier to ask for forgiveness than permission" style is a common Python idiom.


    If you do mean checking for numbers with only one digit after the decimal place, you can adapt this slightly:

    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
    

    Here the IndexError would catch x not containing any '.'s and the ValueError catches x not being interpretable as a float. In general, you may want to split these checks out to report a more useful error to the user (e.g. "Error: couldn't convert '{0}' to float.".format(x)) or even raise an actual Exception.