繁体   English   中英

如何使输入仅接受数学测验中的数字

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

在下面的代码上,我需要添加一些代码,因此当您回答问题时,如果您使用字母而不是字符,它的确会打印出一条消息,但是我真的不知道该怎么做

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

tryinput转换为整数并在失败时捕获异常:

try:
    num = int(input().strip())
except ValueError:
    print("Enter a number only")

与@ ayush-shanker相同的答案,如果要重新提问, 请将其放在循环中

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

甚至更干净一些,请break else子句,以提高可读性:

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

您可能要添加一个计数器,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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