我正在编写一个接受用户输入的程序。
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
只要用户输入有意义的数据,该程序就会按预期运行。
Please enter your age: 23
You are able to vote in the United States!
但如果用户输入无效数据,它将失败:
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in <module>
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
我希望程序不再崩溃,而是再次请求输入。像这样:
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
我如何请求有效输入而不是崩溃或接受无效值(例如 -1
)?
原文由 Kevin 发布,翻译遵循 CC BY-SA 4.0 许可协议
完成此操作的最简单方法是将
input
方法放入 while 循环中。当输入错误时使用continue
,当你满意时使用---break
退出循环。当您的输入可能引发异常时
使用
try
和except
检测用户何时输入无法解析的数据。实施您自己的验证规则
如果要拒绝 Python 可以成功解析的值,可以添加自己的验证逻辑。
结合异常处理和自定义验证
上述两种技术都可以组合成一个循环。
将它全部封装在一个函数中
如果您需要向用户询问很多不同的值,将这段代码放在一个函数中可能会很有用,这样您就不必每次都重新输入。
把它们放在一起
你可以扩展这个想法来制作一个非常通用的输入函数:
用法如:
常见的陷阱,以及为什么要避免它们
冗余语句的冗余使用
input
语句这种方法有效,但通常被认为是糟糕的风格:
它最初看起来很有吸引力,因为它比
while True
方法更短,但它违反了软件开发的 “不要重复自己” 原则。这会增加系统中出现错误的可能性。如果您想通过将input
更改为raw_input
向后移植到 2.7,但不小心只更改了上面的第一个input
怎么办?这是一个SyntaxError
等待发生。递归会破坏你的堆栈
如果您刚刚了解递归,您可能会想在
get_non_negative_int
中使用它,这样您就可以处理 while 循环。这在大多数情况下似乎工作正常,但如果用户输入无效数据的次数足够多,脚本将以
RuntimeError: maximum recursion depth exceeded
终止。你可能会认为“没有傻子会连续犯 1000 次错误”,但你低估了傻子的聪明才智!