Search code examples
pythonpython-2.7promptraw-input

How to make the raw_input prompt automatically read a string from a previous list?


I have created a list like so:

names=["Tom", "Dick", "Harry"]

I want to use these list elements in the prompt for a raw_input.

For example I would like the next line to read: a=raw_input("What is Tom's height?") except that in this form it is hard coded so that the prompt for a will always ask for Tom's height.

I would like the code to be more flexible so that any change to the list element would automatically be updated in the prompt. For example if I changed the list to names=["Matthew", "Sarah", "Jane"] I would like the prompt for a to ask for Matthew's height so that it is always reading the first element of the list.

How can I make it so that the prompt will automatically change if the elements in the list change?


Solution

  • If you want to prompt the user for every name in the list:

    names=["Tom", "Dick", "Harry"]
    for name in names:
        a = raw_input("What is {}'s height? ".format(name))
    

    EDIT:

    To store the results in a list (as per request in comment):

    names=["Tom", "Dick", "Harry"]
    results = []
    for name in names:
        results.append(raw_input("What is {}'s height? ".format(name)))