python:如果条目不是提示的可接受参数,则如何重新询问

时间:2013-11-28 08:45:01

标签: python loops for-loop

我现在只对for循环感到满意所以我已经尝试了我能在那里取得的最小成功。如果我问用户他们是否想要A,B或C并且用户输入D,而不是仅仅说它无效并继续前进,我希望程序再次询问,直到它使用raw_input获得有效答案。 / p>

谢谢!

2 个答案:

答案 0 :(得分:2)

这是一个匿名函数,可以执行您想要的操作。

def get_user_choice(prompt, choices):
    while True:
        choice = raw_input(prompt)
        if choice in choices:
            return choice
        else:
            print 'choice must be in: {}'.format(choices)

使用它:

>>> get_user_choice('choose an option in A, B, C: ', ['A', 'B', 'C'])
choose an option in A, B, C: A
'A'
>>> get_user_choice('choose an option in A, B, C: ', ['A', 'B', 'C'])
choose an option in A, B, C: D
choice must be in: ['A', 'B', 'C']
choose an option in A, B, C: B
'B'

注意:我没有提供太多信息来帮助你,因为我相信你应该自己解决大部分问题,但同时你应该有一些工作解决方案。

答案 1 :(得分:0)

或者这个

answers = ['a', 'b','c']

while True:
    user_input = raw_input("Input> ")
    if user_input in answers:
        break

print "'{0}'' has been chosen".format(user_input)