python面对用户无意义输入的解决

问题

正在编写一个接受用户输入的程序。

#note:Python2.7usersshoulduse`raw_input`,theequivalentof3.X's`input`
age=int(input("Pleaseenteryourage:"))
ifage>=18:
print("YouareabletovoteintheUnitedStates!")
else:
print("YouarenotabletovoteintheUnitedStates.")

只要用户输入有意义的数据,程序就会按预期工作。

C:\Python\Projects>canyouvote.py
Pleaseenteryourage:23
YouareabletovoteintheUnitedStates!

但如果用户输入无效数据,它就会失败:

C:\Python\Projects>canyouvote.py
Pleaseenteryourage:dicketysix
Traceback(mostrecentcalllast):
File"canyouvote.py",line1,in<module>
age=int(input("Pleaseenteryourage:"))
ValueError:invalidliteralforint()withbase10:'dicketysix'

而不是崩溃,我希望程序再次要求输入。像这样:

C:\Python\Projects>canyouvote.py
Pleaseenteryourage:dicketysix
Sorry,Ididn'tunderstandthat.
Pleaseenteryourage:26
YouareabletovoteintheUnitedStates!

当输入无意义的数据时,如何让程序要求有效输入而不是崩溃?

我如何拒绝像 那样的值-1,int在这种情况下这是一个有效但无意义的值?

解决方法

完成此操作的最简单方法是将input方法放入 while 循环中。使用continue时,你会得到错误的输入,并break退出循环。

当您的输入可能引发异常时

使用try和except检测用户何时输入无法解析的数据。

whileTrue:
try:
#Note:Python2.xusersshoulduseraw_input,theequivalentof3.x'sinput
age=int(input("Pleaseenteryourage:"))
exceptValueError:
print("Sorry,Ididn'tunderstandthat.")
#bettertryagain...Returntothestartoftheloop
continue
else:
#agewassuccessfullyparsed!
#we'rereadytoexittheloop.
break
ifage>=18:
print("YouareabletovoteintheUnitedStates!")
else:
print("YouarenotabletovoteintheUnitedStates.")

实现你自己的验证规则

如果要拒绝 Python 可以成功解析的值,可以添加自己的验证逻辑。

whileTrue:
data=input("Pleaseenteraloudmessage(mustbeallcaps):")
ifnotdata.isupper():
print("Sorry,yourresponsewasnotloudenough.")
continue
else:
#we'rehappywiththevaluegiven.
#we'rereadytoexittheloop.
break

whileTrue:
data=input("PickananswerfromAtoD:")
ifdata.lower()notin('a','b','c','d'):
print("Notanappropriatechoice.")
else:
Break

结合异常处理和自定义验证

以上两种技术都可以组合成一个循环。

whileTrue:
try:
age=int(input("Pleaseenteryourage:"))
exceptValueError:
print("Sorry,Ididn'tunderstandthat.")
continue

ifage<0:
print("Sorry,yourresponsemustnotbenegative.")
continue
else:
#agewassuccessfullyparsed,andwe'rehappywithitsvalue.
#we'rereadytoexittheloop.
break
ifage>=18:
print("YouareabletovoteintheUnitedStates!")
else:
print("YouarenotabletovoteintheUnitedStates.")
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。