简体   繁体   English

如何不断提示用户输入?

[英]How to continuously prompt for user input?

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.在其中包含 return 的每一行中,它只是调用了一个先前定义的函数。 The products and part are dictionaries, defined previously. productspart是字典,之前定义过。

I can only use the builtin functions.我只能使用内置函数。

You've done most of the work, you just need this:你已经完成了大部分工作,你只需要这个:

while True:
    print interact()

I would do it with a while loop.我会用一个while循环来做。 Like This:像这样:

while True:
    com = raw_input('Command:').split()
    if len(com) == 0:
        break
    elif com[0] == 'i':
        bike_name =  command[1] + ' ' + command[2]
        return get_product_id(products, bike_name)

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看看这个: http : //docs.python.org/2/library/cmd.html

一种方法是将其放入 while 循环中,然后还检查是否有退出输入中断。

Call the method inside an (end-less) loop:在(无端)循环中调用该方法:

while True:
   some_method()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM