[英]How to do User Input Error Handling in Python?
我不知道为什么我以前从未想过这个......但我想知道是否有一种更整洁/更短/更有效的错误处理方式来处理用户输入。 例如,如果我要求用户输入“你好”或“再见”,而他们输入了其他内容,我需要它告诉用户这是错误的并再次询问。
对于我做过的所有编码,我都是这样做的(通常问题更好):
choice = raw_input("hello, goodbye, hey, or laters? ")
while choice not in ("hello","goodbye","hey","laters"):
print "You typed something wrong!"
choice = raw_input("hello,goodbye,hey,or laters? ")
有没有更聪明的方法来做到这一点? 还是我应该坚持我的经历? 这是我用于我编写的所有语言的方法。
对于一个简单的脚本,您拥有它的方式很好。
对于更复杂的系统,您可以有效地编写自己的解析器。
def get_choice(choices):
choice = ""
while choice not in choices:
choice = raw_input("Choose one of [%s]:" % ", ".join(choices))
return choice
choice = get_choice(["hello", "goodbye", "hey", "laters"])
如果您修改代码以始终进入while
循环,则只需将raw_input
放在一行上。
while True:
choice = raw_input("hello, goodbye, hey, or laters? ")
if choice in ("hello","goodbye","hey","laters"):
break
else:
print "You typed something wrong!"
你可以用递归来做
>>> possible = ["hello","goodbye","hey"]
>>> def ask():
... choice = raw_input("hello,goodbye,hey,or laters? ")
... if not choice in possible:
... return ask()
... return choice
...
>>> ask()
hello,goodbye,hey,or laters? d
hello,goodbye,hey,or laters? d
hello,goodbye,hey,or laters? d
hello,goodbye,hey,or laters? hello
'hello'
>>>
你就是这样做的。 尽管取决于您的使用方式,但将选项放在列表中可能更漂亮。
options = ["hello", "goodbye", "hey", "laters"]
while choice not in options:
print "You typed something wrong!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.