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 share in that company? ')
This only works if the user enters an integer
, but I want it to work even if they enter a float
, but not when they enter a string
.
So the user should be able to enter both 9
and 9.2
, but not abc
.
How should I do it?
The isdigit() function returns true if a string contains digits only and false if at least one character is not a digit. However, this function returns false if a string contains a float number even though a floating-point number is a valid string.
The Python isnumeric method has a number of key differences between the Python isdigit method. While the isidigit method checks whether the string contains only digits, the isnumeric method checks whether all the characters are numeric.
The isdigit() method returns True if all characters in a string are digits or Unicode char of a digit. If not, it returns False.
isdigit() only returns true for strings (here consisting of just one character each) contains only digits. Because only digits are passed through, int() always works, it is never called on a letter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With