Using isdigit for floats? Using isdigit for floats? python python

Using isdigit for floats?


EAFP

try:    x = float(a)except ValueError:    print("You must enter a number")


The existing answers are correct in that the more Pythonic way is usually to try...except (i.e. EAFP).

However, if you really want to do the validation, you could remove exactly 1 decimal point before using isdigit().

>>> "124".replace(".", "", 1).isdigit()True>>> "12.4".replace(".", "", 1).isdigit()True>>> "12..4".replace(".", "", 1).isdigit()False>>> "192.168.1.1".replace(".", "", 1).isdigit()False

Notice that this does not treat floats any different from ints however. You could add that check if you really need it though.


Use regular expressions.

import rep = re.compile('\d+(\.\d+)?')a = raw_input('How much is 1 share in that company? ')while p.match(a) == None:    print "You need to write a number!\n"    a = raw_input('How much is 1 share in that company? ')