1

I have included validation in my code in order to ensure only a number can be entered. However when a negative number is entered, the negative number is not accepted by the program as a valid input. How can I solve this? The code is:

while QuestionNo != 11:

num1 = randint(0,10)
num2 = randint(0,10)
opp = choice(Operators)
Answer = (input(str(num1) + '' + (opp) + '' + str(num2) + '='))

while Answer.isdigit() == False:
    print ('Please enter a number and nothing else.')
    Answer = (input(str(num1) + '' + (opp) + '' + str(num2) + '='))

Thanks, John Smith

J.Doe
  • 13
  • 2
  • Possible duplicate of [How do I check if a string is a number (float) in Python?](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python) – Jeff B Nov 05 '15 at 23:14

1 Answers1

1

The isdigit method returns True only if all characters in the string are digits. In the case of negative numbers, they start with a dash (-) which is not a digit.

Besides, you are adding some operator and an equals sign to your Answer variable; which are also not digits.

I think the conventional way to test if a string is valid number in Python, is using the int builtin:

try:
    int(some_string)
    is_valid_number = True

except ValueError:
    is_valid_number = False
alejandro
  • 1,234
  • 1
  • 9
  • 19
  • [Interesting article](http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/) (very similar answer) showing that numbers in non-English scripts are also handled. Cool! – Jeff B Nov 05 '15 at 23:14
  • Thank you, it worked! And sorry @Jeff Bridgman if this was a similar article (whoops!) >_ – J.Doe Nov 08 '15 at 13:31