我有一个来自自动化书籍的简单乘法测验,我想对此进行扩展。我的目标是收集不正确的答案,并在游戏结束时显示出来。但是,代码检查正确答案的方式是使用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*()
函数都是通用的,请参阅文档或调用help(pyip.parameters)
:applyFunc
(可调用,无(:一个可选函数,传递给用户的输入,并返回新值作为输入。您可以使用此函数保存输入并将其原封不动地传递给验证。如果您只想在输入不正确的情况下存储输入,则需要在此函数中再次检查条件。
示例:
import pyinputplus as p import re # hardcoded values for example incorrectAnswers = [] questionNumber = 1 num1 = 2 num2 = 3 prompt = f'#{questionNumber}: {num1} x {num2} = ' def checkAndSaveInput(n): if not (re.match(f'^{num1 * num2}$',n)): incorrectAnswers.append(n) return(n) inp = p.inputStr(prompt, allowRegexes=[f'^{num1 * num2}$'], blockRegexes=[('.*','Incorrect!')], applyFunc=checkAndSaveInput) print("Your wrong answers were:") for a in incorrectAnswers: print(f' {a}')
执行:
#1: 2 x 3 = six Incorrect! #1: 2 x 3 = 4 Incorrect! #1: 2 x 3 = 5 Incorrect! #1: 2 x 3 = 6 Your wrong answers were: six 4 5
-
由于使用上述方法,无论如何都需要再次检查条件,因此也可以直接编写自定义
inputCustom()
函数。以下示例仅使用allowRegexes
和blockRegexes
中的正则表达式来验证是否输入了int
,并且实际结果检查不是用正则表达式而是用简单的数学方法完成的。与上述方法的不同之处在于,这些值实际上只在确保它们与allowRegexes
中的模式匹配之后才传递给检查函数。import pyinputplus as p # hardcoded values for example incorrectAnswers = [] questionNumber = 1 num1 = 2 num2 = 3 prompt = f'#{questionNumber}: {num1} x {num2} = ' def checkAndSaveInput(n): if((num1 * num2) != int(n)): incorrectAnswers.append(n) raise Exception('Incorrect.') else: print('Correct!') inp = p.inputCustom(checkAndSaveInput, prompt=prompt, allowRegexes=[r'^d+$'], blockRegexes=[('.*','Please enter a valid number!')]) print("Your wrong answers were:") for a in incorrectAnswers: print(f' {a}')
执行:
#1: 2 x 3 = six Please enter a valid number! #1: 2 x 3 = 4 Incorrect. #1: 2 x 3 = 5 Incorrect. #1: 2 x 3 = 6 Correct! Your wrong answers were: 4 5