如何持续提示用户输入?
我正在编写一个函数,提示输入,然后根据输入返回不同的结果,然后再次要求输入。我已经让它返回正确的值,但我不确定如何让它再次提示输入。
下面是该函数的实际代码:
def interact():
command = raw_input('Command:')
command = command.split(' ')
if command[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
if command [0] == 'n':
return get_product_name(products, command[1])
if command[0] == 'c':
return compute_cost(products, part, command[1])
if command[0] == 'p':
return get_parts(products, command[1])
在包含 return 的每一行中,它只是调用先前定义的函数。 products
和 part
是之前定义的字典。
我只能使用内置函数。
I'm writing a function that prompts for input and then returns different results based on the input and then asks for input again. I've got it returning the correct values, but I'm not sure how to make it prompt for input again.
Here's the actual code of the function:
def interact():
command = raw_input('Command:')
command = command.split(' ')
if command[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
if command [0] == 'n':
return get_product_name(products, command[1])
if command[0] == 'c':
return compute_cost(products, part, command[1])
if command[0] == 'p':
return get_parts(products, command[1])
In each line with return in it, it is simply calling up a previously defined function. The products
and part
are dictionaries, defined previously.
I can only use the builtin functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会用 while 循环来做。像这样:
I would do it with a while loop. Like This:
你已经完成了大部分工作,你只需要这个:
You've done most of the work, you just need this:
一种方法是将其放入 while 循环中,然后检查退出输入是否会中断。
One way is to put it in a while loop, and then also check for an exit input to break out.
无需花费如此多的精力来编写自己的命令行解释器。
看看这个: http://docs.python.org/2/library/cmd.html
There is no need to take so much pain and write your own command line interpreter.
Look at this: http://docs.python.org/2/library/cmd.html
在(无限)循环内调用该方法:
Call the method inside an (end-less) loop: