您现在的位置是:课程教程文章
python面对用户无意义输入的解决
2023-12-13 23:53课程教程文章 人已围观
2021最新 DevOps 全栈技术实战课(Docker/K8
2021最新 DevOps 全栈技术实战课(Docker/K8打破职业瓶颈进阶高级,汇集运维前沿技术,打通DevOps自动化体系,为2021年职...python IF语法
python IF语法...软件测试 Python Appium 自动化测试开发
软件测试 Python Appium 自动化测试开发课程大纲 01. Appium应用介绍和基础环境准备 02. Android Stdio环境配置和使用 03. A...量身定制的Python+人工智能之人脸识别和语
量身定制的Python+人工智能之人脸识别和语学习资料和课程咨询请加老师微信沟通552462880 本视频以理论与实际相结合为原...
问题
正在编写一个接受用户输入的程序。
#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.")
以上就是python面对用户无意义输入的解决,希望对大家有所帮助。更多Python学习指路:python基础教程
课程教程:python面对用户无意义输入的解决上一篇:python使用语句的常见陷阱
下一篇:没有了