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

时间:2015-12-07 10:20:10

标签: python python-2.7 python-3.x

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

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

2 个答案:

答案 0 :(得分:2)

$(function () { $(".mapToggle").click(function () { $('.toggle-map-button').slideToggle(); // Replace with either 1, or 2. }); }); try转换为整数,如果失败则捕获异常:

input

答案 1 :(得分:0)

与@ 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