-2

Possible Duplicate:
Python - How to check if input is a number (given that input always returns strings)

I need to check a input and send a error message if it's not numerical. How would i do this the best way? Cant seem to find any other posts about it thou i'm shure someone must have asked this question before.

Community
  • 1
  • 1
Sergei
  • 585
  • 4
  • 9
  • 20

4 Answers4

4
 if not value.isdigit():
     raise ValueError("Input must be numeric")

@TokenMacGuy's solution is better if you're getting your input from raw_input(), but otherwise this works.

If you want to loop until you get proper input rather than raise an error, try this:

value = input("Input: ")
while not value.isdigit():
    input("Input must be numeric, please reenter: ")
Rafe Kettler
  • 73,388
  • 19
  • 151
  • 149
3

edit:

>>> while True:
...     try:
...         result = int(raw_input("Enter a Number: "))
...         break
...     except ValueError:
...         print "Input must be a number"
... 
Enter a Number: abc
Input must be a number
Enter a Number: def
Input must be a number
Enter a Number: 123
>>> result
123
>>> 
SingleNegationElimination
  • 144,899
  • 31
  • 254
  • 294
0
while True:
    user_input = raw_input("> Please enter a number:")
    try:
        n = float(user_input)
    except ValueError:
        continue
    else:
        break
Mike Graham
  • 69,495
  • 14
  • 96
  • 129
-1

The isdigit function can be used to test if a string is all digits and is not empty:

val = '255'
val.isdigit()
Zack Bloom
  • 8,199
  • 2
  • 19
  • 26