Python strings have an "isdigit method": case.isdigit()
- that returns True or False.
This method is enough if you want only positive integers - however, if you want to validate also entering numbers with decimal point or negative, it is best to make a function that tries to convert the number within one try...except
and call this function to verify. Then with the minimum code, you accept all syntax variants for numbers (negative, exponential notation, infinity, etc...):
def isnumber(value):
try:
float(value)
except ValueError:
return False
return True
...
if isnumber(case):
...
This method has the following side effect that can sometimes be desirable, but sometimes not: it validates all possible forms of representation of a float in Python - not only the presence of signal and decimal point, but also scientific notation and the special values "Nan" (not a number), "Inifinity" (infinity or infinity) and scientific notation - which allows specifying the position of the decimal point with the prefix "and":
>>> [float(exemplo) for exemplo in ("infinity", "NaN", "1.23e-4")]
[inf, nan, 0.000123]
If this is not desired, a function that does both validations may be better - first detects the characters - and then uses the conversion to float
not to worry if the number is valid (that is: only a decimal point, the sign is the first character, etc...):
def is_simple_number(value):
if not value.strip().replace('-', '').replace('+', '').replace('.', '').isdigit():
return False
try:
float(value)
except ValueError:
return False
return True
Python strings also have methods isnumeric
and isdecimal
- but they are synonymous with isdigit
- neither of the two methods accepts decimal point or sign, for example.
Excellent explanation that one should avoid Exceptions. In my view it is because of performance. There is some other good reason?
– danilo
Because in general there is no exceptional situation there, it is a wrong concept, when one conceptualizes wrong everything goes off the rails. If researching about has a lot of information, right here has a huge amount of my answers about.
– Maniero