-1

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'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Adrian F
  • 13
  • 2
  • Your error message doesn't correspond to the code you claim to be running. `isfloat` and `isNumber` aren't valid [string methods](https://docs.python.org/2/library/stdtypes.html#string-methods). Why not write your own `is_float` function? – jonrsharpe Jun 22 '14 at 08:42
  • 1
    Don't write your code in the `C:\Python27` directory, or any subdirectory under it. – Burhan Khalid Jun 22 '14 at 08:46
  • Do you mean how to check that `x` is a float and contains only one *number after* the decimal point? E.g. `1.2` is OK but `1.23` isn't? – jonrsharpe Jun 22 '14 at 09:01

1 Answers1

4

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437