python – How to check if the string variable value is number?

Question:

I'm developing a program where the user enters a data, then I have to check if the value is a number to proceed with the operation, but if he enters a non-numeric value he is alerted about the invalid value.

I tried to use the type() function but it checks the variable type and not its value, so it's difficult given the fact that the input() function returns the input as a string .

case = input(escolha um valor de 0 a 10)
if type(case) != int:
   print("Digite apenas numeros!")
else:
   #--processo

I thought of formatting the input() with int() but if the user were to type a non-numeric character the program will give an error, when in fact I would like to handle this by asking her to type only numbers.

Answer:

Python strings have an "isdigit" method: case.isdigit() – which returns True or False.

This method is enough if you only want positive integers – however, if you also want to validate input of numbers with decimal or negative points, the best thing is to make a function that tries to convert the number inside a try...except and call that function to check. Then with the minimum of code, you start to accept all syntax variants for numbers (negative, in 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 which is sometimes desirable but sometimes not: it validates all possible ways of representing a float in Python – not only the presence of sign and decimal point, but also scientific notation and the values special "NaN" (not a number), "inifinity" (infinity or infinity) and scientific notation – which allows specification of the decimal point position with the prefix "e":

>>> [float(exemplo) for exemplo in ("infinity", "NaN", "1.23e-4")]                                              
[inf, nan, 0.000123]

If that's not desired, a function that does both validations might be better – first detects the characters – and then uses the conversion to float so you don't have to worry about whether the number is valid (ie: just 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

Strings in Python also have isnumeric and isdecimal methods – but they are synonymous with isdigit – neither method accepts decimal point or sign, for example.

Scroll to Top