python面对用户无意义输入的解决
发布时间:2024-06-30 20:34:35

问题
正在编写一个接受用户输入的程序。
#note:Python2.7usershouldusers`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!
当输入无意义的数据时,程序如何需要有效的输入而不是崩溃?
怎样才能拒绝像? 在这种情况下,int是一个有效但毫无意义的值-1?
解决方法
完成此操作的最简单方法是将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.")以上是python面对用户无意义输入的解决方案,希望对大家有所帮助。更多Python学习指南:python基础教程
