Python, continuously prompting for user input

2019-08-05 02:24发布

This is homework so I'm just after some guidance.

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, just 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, products and part are dictionaries, defined previously.

I can only use the builtin functions

Any help is greatly appreciated!

标签: python input
5条回答
家丑人穷心不美
2楼-- · 2019-08-05 02:50

One way is to put it in a while loop, and then also check for an exit input to break out.

查看更多
孤傲高冷的网名
3楼-- · 2019-08-05 02:58

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

查看更多
我想做一个坏孩纸
4楼-- · 2019-08-05 03:03

Call the method inside an (end-less) loop:

while True:
   some_method()
查看更多
唯我独甜
5楼-- · 2019-08-05 03:11

I would do it with a while loop. 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)
查看更多
Lonely孤独者°
6楼-- · 2019-08-05 03:15

You've done most of the work, you just need this:

while True:
    print interact()
查看更多
登录 后发表回答