Reputation: 33
on the code below i need to add some code so when you are answering a question it does print out a message if you use letters instead of characters but i dont really know how to do it
import random
import re
question_number = 0
score=0
ops = {'+','-','*'}
print ("this is a short maths quiz")
name = input ("what is your name")
if not re.match("^[a-z]*$", name):
print ("Error! Only letters a-z allowed please restart the test!")
exit()
elif len(name) > 15:
print ("Error! Only 15 characters allowed please restart the test!")
exit()
print ("ok "+name+" im going to start the quiz now")
while question_number < 10:
number1 = random.randint(1,10)
number2 = random.randint(1,10)
op = random.choice(list(ops))
print ("what is ......")
print(number1, op, number2)
user_input=int(input())
if op == "+":
answer = (number1+number2)
elif op == "-":
answer = (number1-number2)
elif op == "*":
answer = (number1*number2)
if user_input == answer:
print("Well done")
score = score + 1
question_number = question_number + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
if question_number==10:
print("thank you for playing my quiz "+name+" i am calculating your score now")
print("your score is" , score, "out of 10")
Upvotes: 0
Views: 102
Reputation: 15987
Same answer as @ayush-shanker, and put it in a loop if you want to re-ask:
while True:
try:
num = int(input().strip())
# ValueError caused on line above if it's not an int
break # no error occurred, so exit loop
except ValueError:
print("Enter a number only")
Or even cleaner, break
in the else
clause, for better readability:
while True:
try:
num = int(input().strip())
# ValueError caused on line above if it's not an int
except ValueError:
print("Enter a number only")
else:
# no error occurred, so exit loop
break
You may want to add a counter like:
tries = 0 # number of tries for validity, not right or wrong.
while True and tries < 10:
try:
num = int(input().strip())
# ValueError caused on line above if it's not an int
except ValueError:
tries += 1
print("Enter a number only")
else:
# no error occurred, so exit loop
break
Upvotes: 0
Reputation: 3945
try
to convert input
to integer and catch the exception if it fails:
try:
num = int(input().strip())
except ValueError:
print("Enter a number only")
Upvotes: 2