-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.

0

4 Answers 4

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: ") 
Sign up to request clarification or add additional context in comments.

2 Comments

I'm using input(), but the thing is i need the message to be something like "Input must be numeric, please reenter: "
@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.
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 >>> 

Comments

0
while True: user_input = raw_input("> Please enter a number:") try: n = float(user_input) except ValueError: continue else: break 

Comments

-1

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

val = '255' val.isdigit() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.