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.