I am trying to write a function in python that takes user input and stores it in a list

时间:2015-04-29 00:26:48

标签: python

right now I believe I have started off the loop correctly but for some reason it stops after two iterations, and when I print the list, there are no values. I know its a really beginner question, but I am really having trouble with this.

def string():
    """Grabs user input and stores it in a list"""
    vegies = []
    choice = None

while choice != "Q":
    choice = input("Please select a vegetable or fruit to the list or Q to quit:")
    vegies = vegies.append(choice)

2 个答案:

答案 0 :(得分:3)

The problem is that you are doing veggies = veggies.append(something). The method append does not return any value, so it is wrong to write variable = list.append() once, as it won't return anything, variable will hold None as value.

In order to use append, use only veggies.append(something)

def string(): #Although not wrong in terms of syntax, it is not recommended to name the function 'string'
 """Grabs user input and stores it in a list"""
    vegies = []
    choice = None

    while choice != "Q":
        choice = input("Please select a vegetable or fruit to the list or Q to quit:")
        vegies.append(choice)

答案 1 :(得分:0)

A much easier route (Note : I am using python 2.7.9, you are using python 3.x so just substitute raw_input with input

vegies = raw_input('Enter vegetable or fruit seperated by spaces: ')
print vegies.split(' ')

Output:

Enter vegetable or fruit seperated by spaces: apple banana orange
['apple', 'banana', 'orange']

You can very do veggie_list = vegies.split(' ') to store the list and carry on with your program