如果Python中的输入无效,如何再次发出程序提示?
在用户选择有效选项之前,我需要再次询问这些选项如果Python中的输入无效,如何再次发出程序提示?,python,Python,在用户选择有效选项之前,我需要再次询问这些选项 choice = input('Please choose 1,2,3\n') if choice == 1: print('You have chosen the first option') elif choice == 2: print('You have chosen the second option') elif choice == 3: print('You have chosen the third option') els
choice = input('Please choose 1,2,3\n')
if choice == 1:
print('You have chosen the first option')
elif choice == 2:
print('You have chosen the second option')
elif choice == 3:
print('You have chosen the third option')
else:
print('This is not an option, please try again.')
试试这个:
valid = False
while(valid == False):
choice = input("Please choose 1,2,3\n")
if choice == 1:
valid = True
print('You have chosen the first option')
elif choice == 2:
valid = True
print('You have chosen the second option')
elif choice == 3:
valid = True
print('You have chosen the third option')
else:
valid = False
print('This is not an option, please try again.')
也许我错了,因为我只是一个黑客,但我相信一个更“蟒蛇式”的答案是:
choices = {1:'first', 2:'second', 3:'third'}
while True:
choice = input('Please choose 1, 2, or 3.\n')
try:
print 'You have chosen the {} option.'.format(choices[choice])
break
except KeyError:
print 'This is not an option; please try again.'
或者至少:
while True:
choice = input('Please choose 1, 2, or 3.\n')
if choice == 1:
print 'You have chosen the first option'
break
elif choice == 2:
print 'You have chosen the second option'
break
elif choice == 3:
print 'You have chosen the third option'
break
else:
print 'This is not an option; please try again.'
这两种方法都避免了创建不必要的测试变量,第一种方法减少了所需的总体代码
对于Python3,我认为在打印的语句周围添加括号应该是唯一的更改。该问题没有使用版本标记。您可以将其放入函数中,该函数接受所需的提示和有效选择,并且仅在进行有效输入时返回
def get_input(prompt, choices):
while True:
choice = input("%s %s or %s: " % (prompt, ", ".join(choices[:-1]), choices[-1]))
if str(choice) in choices:
return choice
choice = get_input("Please choose", ["1", "2", "3"])
print("You have chosen {}".format(choice))
这将提供以下类型的输出:
Please choose 1, 2 or 3: 1
You have chosen 1
你学过循环吗?您应该学习循环。去吧。它们在几乎任何编程语言中都是基本的。请阅读
,而循环在Python中用于C/C++结构,因此我不得不为pythonIt三思。它说“false”不是定义的,而是大写false和true。您不断输入错误或完全无效的Python语法的代码。据我所知,在C/C++中,测试代码以确保其编译和运行与在Python中一样重要。感谢您提供这样的逻辑回答,但我建议在选项中使用if int(choice):print“You have selected the{}option.”。format(choices[choice])
--“1”、“2”,“3”也可以是选项
dict中的字符串,这样在转换为int时就省去了一些麻烦。我会为“quit”添加一个选项“q”。对于那些没有足够复杂的能力来Ctrl-C out的用户来说,更令人愉快的是,如果您将逻辑连接到GUI中,您已经有了“取消”按钮的功能。@美联社,我以前也总是这样做,但我似乎记得有一种解释,即对于大型词典来说,它的效率较低。我意识到,在这种情况下,这是微不足道的,但我养成了捕捉keyrerror的习惯。经进一步检查,这似乎要视情况而定,基于清晰度,你的方法只是将我的方法略胜一筹。@Tom这是可能的,但我无法想象任何一种方法的效率都会降低。检查哈希(dict)中的成员身份是O(1)——非常快,即使在大型数据集上也是如此。为了抛出一个KeyError,无论如何都需要进行查找工作。