简体   繁体   中英

how to make an input only accept numbers on a maths quiz

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")

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM