首页IT科技python打错了(python面对用户无意义输入的解决)

python打错了(python面对用户无意义输入的解决)

时间2025-05-01 17:03:45分类IT科技浏览2866
导读:问题...

问题

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

#note:Python2.7usersshoulduse`raw_input`,theequivalentof3.Xs`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,Ididntunderstandthat. Pleaseenteryourage:26 YouareabletovoteintheUnitedStates!

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

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

解决方法

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

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

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

whileTrue: try: #Note:Python2.xusersshoulduseraw_input,theequivalentof3.xsinput age=int(input("Pleaseenteryourage:")) exceptValueError: print("Sorry,Ididntunderstandthat.") #bettertryagain...Returntothestartoftheloop continue else: #agewassuccessfullyparsed! #werereadytoexittheloop. break ifage>=18: print("YouareabletovoteintheUnitedStates!") else: print("YouarenotabletovoteintheUnitedStates.")

实现你自己的验证规则

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

whileTrue: data=input("Pleaseenteraloudmessage(mustbeallcaps):") ifnotdata.isupper(): print("Sorry,yourresponsewasnotloudenough.") continue else: #werehappywiththevaluegiven. #werereadytoexittheloop. 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,Ididntunderstandthat.") continue ifage<0: print("Sorry,yourresponsemustnotbenegative.") continue else: #agewassuccessfullyparsed,andwerehappywithitsvalue. #werereadytoexittheloop. break ifage>=18: print("YouareabletovoteintheUnitedStates!") else: print("YouarenotabletovoteintheUnitedStates.")

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
python自带的idle怎么用(python中IDLE是什么意思) python里raise(python中raise是什么)