0

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Sean
  • 107
  • 1
  • 1
  • 6
  • http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming – Ignacio Vazquez-Abrams Apr 05 '11 at 03:12
  • Sorry but asking for such a basic question how writing a loop is tutorial level: google "python tutorial" and read up on "loops" –  Apr 05 '11 at 03:14
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – ruohola May 04 '19 at 14:20

5 Answers5

4

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)
moestly
  • 1,681
  • 15
  • 19
3

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

while True:
    print interact()
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
2

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

battery
  • 502
  • 6
  • 26
1

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

Dimitar
  • 2,392
  • 2
  • 19
  • 28
0

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

while True:
   some_method()