输入验证即检查用户输入值的格式是否正确
一、PyInputPlus模块
该模块包含与input()类似的、用于多种数据(数字、日期、E-mail地址等)的函数。如果用户输入无效内容,则会提示再次输入
需要使用pip额外安装
- inputStr()
- inputNum():确保用户输入数字并返回int或float值
- inputChoice():确保用户输入系统提供的选项
- inputMenu():在上述基础上提供一个带有数字或字母选项的菜单
- inputDatetime()
- inputYesNo():输入yes或no响应
- pnputBool():接收True或False响应
- inputEmail()
- inputFilepath()
- inputPassword()
1、关键字参数min、max、greaterThan和lessThan
接收int和float数的 inputNum(),inputInt()和inputFloat()函数还具有上述关键字参数,用于指定有效值范围
response = pyip.inputNum("Please enter:",min = 3,lessThan=5)
2、关键字参数blank
默认情况下,除非将blank设置为True,否则必须有输入值
默认情况时:
有blank=True:
3、关键字参数limit、timeout和default
limit和timeout使输入次数有限化,可规定输入多少次或一定时间后停止输入
respone = pyip.inputNum(limit=2):只许输入2次
respone = pyip.inputNum(timeout=20):只许输入20s
如果用户未能提供有效输入,那么会引发RetryLimitException和TimeoutException异常,这时,如果添加default关键字,就不会引发异常,而是将default值赋予respone变量
response = pyip.inputNum("Please enter:",limit=2,default="you are wrong")
print("当前response值为%s"%response)
4、关键字参数allowRegexes和blockRegexes
使用正则表达式指定输入是否被接受
allowRegexes参数是一个列表,其中每个元素都是一个字符串,代表一个正则表达式。如果用户的输入与列表中的任何一个正则表达式匹配,那么输入将被接受
blockRegexes参数是一个列表,其中每个元素都是一个元组,元组包含两个部分:
- 正则表达式:用于定义不希望用户输入的模式。
- 错误消息:当用户的输入与正则表达式匹配时显示的消息。
例如:
allowRegexes让inputNum()函数在接收常规数字基础上再接收罗马数字 :
response = pyip.inputNum("Please enter:",allowRegexes=[r"(I|V|X|L|C|D|M)+",r"zero"])
blockRegexes让inputNum()不接受偶数作为有效输入:
response = pyip.inputNum("Please enter:",blockRegexes=[r"[02468]$"])
5、将自定义验证函数传递给inputCustom()
我希望用户输入一个数字,每位数字相加和为10
def addsUpToTen(num):
sum = 0
number = int(num)
while number > 0:
digit = number % 10
sum += digit
number //= 10
if sum != 10:
raise Exception("The sum is %s, not 10"%sum)
return int(num)
response = pyip.inputCustom(addsUpToTen)
inputCustom()函数还支持常规的PyInputPlus功能,即那些关键字参数
如果正则表达式不好写时可以使用该函数
二、项目--乘法测验
创建一个程序,向用户提出10个乘法问题,其中有效的输入是问题的正确答案
import pyinputplus as pyip
import random,time
numberOfQuestions = 10
correctAnswers = 0
for question in range(numberOfQuestions):
num1 = random.randint(1,9)
num2 = random.randint(1,9)
prompt = "%s: %s x %s" % (question+1,num1,num2)
try:
response = pyip.inputStr(prompt,
allowRegexes=["^%s$"%(num1*num2)], #^$共用表示匹配整个模式
blockRegexes=[(r".*","Incorrect!")], #输入任何非空字符串,这个正则表达式都会匹配。匹配后将显示错误消息 "Incorrect"。
timeout=5,limit=2)
except pyip.TimeoutException:
print("Out of time !")
except pyip.RetryLimitException:
print("Out of retry limit")
else:
print("correct!")
correctAnswers += 1
time.sleep(1)
print("Score: %f"%(correctAnswers/numberOfQuestions))