python:如果一个条目不是可接受的提示参数,如何重新提问 [英] python: If an entry is not an acceptable parameter for a prompt, how to re-ask

查看:170
本文介绍了python:如果一个条目不是可接受的提示参数,如何重新提问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在只对for循环感到舒服,所以我尝试了我能在那里取得最小的成功。如果我问用户是否需要A,B或C,而用户输入D,而不是仅仅说它是无效的,那么我希望程序再次询问,直到使用raw_input得到有效答案。 / p>

谢谢!

解决方案

这是一个匿名函数,

$ p $ def get_user_choice(提示,选项):
,True:
choice = raw_input(提示)
如果选择了选择:
返回选择
else:
print'选项必须在:{}'。格式(选项)

 >>> ;> get_user_choice('在A,B,C:',['A','B','C']中选择一个选项)
在A,B,C中选择一个选项:A
'A '
>>> get_user_choice('在A,B,C:',['A','B','C']中选择一个选项)
在A,B,C中选择一个选项:D
choice必须在A:B,B:B,B: / pre>

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


Im only comfortable with for loops at the moment so I've tried what I can there with minimal success. If I asked the user if they want A, B, or C and the user inputs D, instead of just saying it is invalid and moving on, i'd like the program to ask again until it gets a valid answer using raw_input.

Thanks!

解决方案

Here is an anonymous function that does what you want.

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)

Using it:

>>> 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'

Note: I have not given too much information to help you, because I believe you should figure most of this out on your own, but meanwhile you should have some kind of working solution.

这篇关于python:如果一个条目不是可接受的提示参数,如何重新提问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆