-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
  • 21

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
  • 75,757
  • 21
  • 156
  • 151
  • I'm using input(), but the thing is i need the message to be something like "Input must be numeric, please reenter: " – Sergei Aug 11 '11 at 18:55
  • @Sergei, What are you going to do if it's numeric? Convert it to a number? If so, don't check, just do the conversion. – Mike Graham Aug 12 '11 at 14:38
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
  • 151,563
  • 33
  • 264
  • 304
0
while True:
    user_input = raw_input("> Please enter a number:")
    try:
        n = float(user_input)
    except ValueError:
        continue
    else:
        break
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
-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,309
  • 2
  • 20
  • 27