如何在Python中进行用户输入错误处理?

问题描述 投票:0回答:4

我不知道为什么我以前从未想到过……但是我想知道是否存在一种更整洁,更短或更有效的错误处理用户输入的方式。例如,如果我要求用户输入“ hello”或“再见”,而他们又输入了其他内容,则我需要它告诉用户这是错误的,然后再次询问。

对于我曾经做过的所有编码,这就是我做过的方式(通常问题更好):

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? ")

是否有更聪明的方法?还是我应该坚持自己的经历?这是我用于编写的所有语言的方法。

python user-input
4个回答
4
投票
对于更复杂的系统,您可以有效地编写自己的解析器。

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"])


1
投票
>>> 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' >>>

0
投票
options = ["hello", "goodbye", "hey", "laters"] while choice not in options: print "You typed something wrong!"

0
投票
while True: choice = raw_input("hello, goodbye, hey, or laters? ") if choice in ("hello","goodbye","hey","laters"): break else: print "You typed something wrong!"
© www.soinside.com 2019 - 2024. All rights reserved.