python:如果一个条目不是可接受的提示参数,如何重新提问 [英] python: If an entry is not an acceptable parameter for a prompt, how to re-ask
问题描述
谢谢!
这是一个匿名函数,
$ p $ def get_user_choice(提示,选项):
,True:
choice = raw_input(提示)
如果选择了选择:
返回选择
else:
print'选项必须在:{}'。格式(选项)
$ c $
>>> ;> 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屋!