I'm currently creating a quiz to test children's ability to add, subtract and multiply two numbers together. You can see the code below as to what I have developed so far:
from random import randint
import re
first_number = randint(30,60)
second_number = randint(30,60)
correct_ans = str(first_number - second_number)
while True:
user_input = input("%s - %s = " %(first_number, second_number))
if re.search(r'[\d]', user_input):
print("Error. You have entered a non - integer character. The question will be asked again.")
elif re.search(r'[0-9]', user_input):
if (user_input == correct_ans):
print("Correct! Well done!")
break
else:
print("Your answer is incorrect. The correct answer was %s" %(correct_ans))
break
To explain the program briefly -
There are two random numbers generated, and this function ONLY multiplies the numbers together. A while loop asks the user for the correct result. Now, the first regular expression analyses the input to see if they have entered any non - digit characters (punctuation, letters) etc. If they have, they receive a message and the question is asked again.
Now, the second part of the if statement then checks to see that if they have entered a number, and if they have, then the program checks to see if the input is correct to the correct_ans. If it is, they receive a message saying well done! and the program breaks. If they get it wrong, the program outputs a message and they still get it wrong.
The issue that I'm having is that the IDLE is outputting the first message "Error, you have entered..." all the time, like this:
50 - 60 = -10
Error. You have entered a non - integer character. The question will be asked again.
50 - 60 =
How can I solve this? And more importantly, how can I get the computer to accept negative values for the subtraction operation, since it has a '-' and considers it a punctuation?
'10'.isdigit()andabs(-10)