【发布时间】:2020-10-13 08:06:43
【问题描述】:
我需要帮助验证我提出的(随机)问题的输入,以确保用户输入的只是一个数字,而不是字母或任何其他随机字符。此外,除了验证之外,还应该有一条错误消息通知用户他们做错了什么,并重复他们做问题的机会。
到目前为止,我需要验证的代码部分如下:
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': operator.add,'-': operator.sub,'*': operator.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("\nWhat is {} {} {}?".format(x, opt, y))
userAnswer= int(input("\nYour answer: "))
if userAnswer != answer: #validate users answer to correct answer
print ("\nIncorrect. The right answer is",answer,"")
print ("\n============= 8 =============")
return False
else:
print("\nCorrect!")
print ("\n============= 8 =============")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1
print("\n{}: You got {}/{} questions correct.".format(name, score, questions,))
提前致谢!
【问题讨论】:
标签: python