如何在Python中将用户输入添加到列表中

时间:2014-01-10 11:39:10

标签: python list shopping

print ('This is your Shopping List')          
firstItem = input('Enter 1st item: ')         
print (firstItem)             
secondItem = input('Enter 2nd item: ')           
print (secondItem)  

如何列出用户所说的内容,然后在结束时将其打印出来?

另外,我如何询问他们是否在列表中添加了足够的项目?如果他们拒绝,那么它将打印出已存储的项目列表。

谢谢,我是新手,所以我真的不知道。

2 个答案:

答案 0 :(得分:9)

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

答案 1 :(得分:4)

下面的代码允许用户输入项目,直到他们按下回车键停止:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: