How to check if the variable string value is number?

Asked

Viewed 38,715 times

16

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

I tried to use the function type() but it checks the type of variable and not its value, so it is difficult given the fact that the function input() returns to enter as 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 typed a non-numeric character the program will present error, when in fact I would like to treat this by asking her to type only numbers.

11 answers

18


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.

10

Can use isdigit().

num = input("escolha um valor de 0 a 10")
if not num.isdigit():
    print("Digite apenas numeros!")
print(num)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I think it’s a good idea to use an exception to handle this. There’s a huge abuse in every language. Exception is useful, but today almost every use ends up being a conceptual error at least. Although perhaps in Python they consider acceptable for lack of a better mechanism.

If you want something beyond this it would be interesting to create a function that deals with the criteria you need. And if you need performance maybe it pays to do it in C and integrate with Python.

  • Excellent explanation that one should avoid Exceptions. In my view it is because of performance. There is some other good reason?

  • 1

    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.

6

I missed an answer with regular expression. For whole patterns:

import re # pacote com as rotinas de expressão regular
pattern_int = re.compile(r"(0|-?[1-9][0-9]*)")

entrada = input()
if pattern_int.match(entrada):
    print(entrada + " é um número inteiro")
else:
    print(entrada + " não é um número inteiro")

Behold functioning on the ideone.

5

Check if it is int:

def isInt(value):
  try:
    int(value)
    return True
  except:
    return False

I hope I’ve helped!

  • 4

    it is not legal to use 'except" without specifying the generated exception - in the case of Valueerror. In Python 3 this is even a syntax error - but the problem is that if some other type of error happens in the Try section, you will have a rpoblema in the code that will be very difficult to locate.

5

0

def henum(num):
    numeros= ['0','1','2','3','4','5','6','7','8','9']
    for digito in num:
        if digito in numeros:
            return True
        else:
            return False

num = input("Digite um número: ")
if henum(num):
    print("é numero!!!")
else:
     print("Não é numero!!!")
  • 1

    And what difference does it make num.isdigit(), as quoted in this answer?

  • Your solution is absolutely correct, just wanted to illustrate, using another way to address the problem. I often demonstrate to my students how some functions or methods perform the procedures, so that they can understand the logic. Hugs.

  • 1

    you can edit the answer, and put this comment that contextualizes your code and explains your motivation at the beginning of it.

  • 1

    Then I suggest you edit your answer and explain, in fact, something. So far you’ve only responded with one-off code that may not make sense to many community users.

0

Another interesting way to resolve this issue is by using Assignment Expressions, approached by PEP 572. With this technique the code would be:

while not (n := input('Valor entre 0 e 10: ')).isdigit() or (n := int(n)) < 0 or n > 10:
    print('Valor INVÁLIDO!')

print(n)

When we run this code three conditions are checked:

  1. Checks if what was typed is NOT a digit;
  2. Checks if the string converted to integer is less than "0";
  3. Checks if the string converted to integer is greater than "10".

Case, one of these three conditions is True, we will receive the message:

Valor INVÁLIDO!

And case all the three conditions are False, the repeat loop is finished.

To make the code more understandable I decided to display the entered value, if the three checks are False.

Where the three verifications are False, means to say that the entered value is a number and is between 0 and 10, including 0 and 10.

0

I’ve been starting in Python for a few weeks. In the example I was studying "TUPLES" it does not have the above functions that begin with "is" (as isInt(), isdigit(), etc....).

Then with the try solved quietly. Follow my example below.

def soma_todos_numeros(*args):

    try:

        return sum(args)

    except:

        return False


print(soma_todos_numeros('a'))

print(soma_todos_numeros(1))

print(soma_todos_numeros(2,3))

print(soma_todos_numeros(2,3,4))

print(soma_todos_numeros(3,4,5,6))

-1

Good evening, I’m new to Python and here too, but I managed to solve this way to floating point:

str(price).replace('.','').isnumeric()

I believe this way is simpler, I hope it helps

-2

def Verificar_tipo(num):
    try:
        num / 2

    except TypeError:
        print("Não é um numero")
        return exit()

    else:
        exit()


Verificar_tipo('Número')
  • 2

    It is not a reliable test, since num can be an instance of a type that overloads the operator /. For example, an instance of pathlib.Path owns the operator / and would be treaty as a number.

-3

Use the verification method already in Python, the is. See below your rectified code:

case = input(escolha um valor de 0 a 10)  
verificação = isnumeric(case)  

if verificação == True:  
    print ('O número digitado foi {}'.format(case))  
elif verificação == False:  
    print ('Digite apenas numeros!')  

The isnumeric checks if in the variable you created case added only numbers, if you have something other than numbers (letters or spaces) it returns the negative result False. I assign the check result to a new variable I called verificação and made the conditional blocks attached to it. If verificação for True, ie have only numbers, display the number typed, if False, display "Digite apenas numeros!".

PS: Remember to indent the print within the condition, I could not write here in this editor the spaces to the left of the print.

  • 3

    I voted negative basically because it’s not even a valid Python code. 1) Quotes are missing from the function input; 2) The function of isnumeric there is no - perhaps you wanted to refer to str.isnumeric; 3) No need to do verificação == True, only if verificação suffice; 4) elif to check if it is false? Or it is true or false, if it is not true it will be false, you do not need to check again; you can use the else.

  • Regarding code formatting, read the formatting guide.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.