a = raw_input(\'How much is 1 share in that company? \')
while not a.isdigit():
print(\"You need to write a number!\\n\")
a = raw_input(\'How much is 1 shar
Building on dan04's answer:
def isDigit(x):
try:
float(x)
return True
except ValueError:
return False
usage:
isDigit(3) # True
isDigit(3.1) # True
isDigit("3") # True
isDigit("3.1") # True
isDigit("hi") # False
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.