我有一个来自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}')
实际上,你可以通过不同的方式实现你想要的
有一个可选参数
applyFunc
,它是所有input*()
函数的公共参数,请参见documentation或调用help(pyip.parameters)
:您可以使用此函数保存输入,并将其原封不动地传递给验证。如果您只想在输入不正确的情况下存储输入,则需要在此函数中再次检查条件
例如:
执行:
由于使用上述方法,您仍然需要再次检查条件,因此也可以直接编写custom ^{} function 。下面的示例仅使用中的模式匹配
allowRegexes
和blockRegexes
中的正则表达式来验证是否输入了int
,并且实际的结果检查不是使用正则表达式而是使用简单的数学进行的。与上述方法不同的是,值实际上只在之后传递给检查函数,确保它们与^{执行:
相关问题 更多 >
编程相关推荐