How to check if the string variable value is number?

5

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

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

    
asked by anonymous 03.06.2017 / 21:07

5 answers

5

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

This method is sufficient if you want only positive integers - however, if you want to validate also entry of numbers with decimal point or negatives, it is best to do a function that tries to convert the number inside a try...except and call this function to check. Then with the minimum of code, you accept all variants of syntax for numbers (negative, exponential notation, infinite, etc ...):

def isnumber(value):
    try:
         float(value)
    except ValueError:
         return False
    return True

...

if isnumber(case):
    ...
    
03.06.2017 / 21:12
5

You can use isdigit() .

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

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

Please do not make the mistake of using an exception to deal with this. There is enormous abuse in all languages. Exception is useful, but today almost every use ends up being a mistake in the least conceptual. Although perhaps in Python consider acceptable for lack of a better mechanism.

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

    
03.06.2017 / 21:51
4

Try converting it to an int

 try:
   val = int(userInput)
 except ValueError:
   print("Não é número")

source How to check if string input is a number?

    
03.06.2017 / 21:25
3

Check if int:

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

I hope I have helped!

    
03.06.2017 / 21:10
2

I missed a regular expression response. For integer 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")

See working on ideone .

    
04.06.2017 / 01:49