【发布时间】:2020-08-08 05:14:35
【问题描述】:
我有一个来自automate book 的简单乘法测验,我想扩展它。
我的目标是收集错误答案并在游戏结束时显示它们。
但是,代码检查正确答案的方式是使用blockRegexes 参数阻止除正确答案之外的所有内容。
我已经尝试检查验证异常,但这不起作用。
这是我的代码:
import pyinputplus as p
import random, time
numberOfQuestions = 10
correctAnswers = 0
incorrectAnswers = []
#def blockRegRaiseExcep(text):
# because in a regular inputStr it won't raise an exception if I match the blocked regex.
for questionNumber in range(numberOfQuestions):
# Pick two random numbers:
num1 = random.randint(0,9)
num2 = random.randint(0,9)
prompt = f'#{questionNumber}: {num1} x {num2} = '
try:
# Right answers are handled by allowRegexes.
# Wrong answers are handled by blockRegexes, with a custom message.
inp = p.inputStr(prompt,allowRegexes=[f'^{num1 * num2}$'], # allow only the right number! great.
blockRegexes=[('.*','Incorrect!')], # we are blocking everything, basically, love it!
timeout=8, limit=3)
except p.TimeoutException:
print(f'Out of time!\nCorrect answer is {num1 * num2}')
except p.RetryLimitException:
print(f'Out of tries!\nCorrect answer is {num1 * num2}')
else:
# This block runs if no exceptions were raised by the try block.
print('Correct!')
correctAnswers += 1
time.sleep(1) # Brief pause to let the user read the result.
print(f'Score: {correctAnswers} / {numberOfQuestions}')
【问题讨论】:
标签: python python-3.x regex validation input