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

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

用户如何输入列表并在完成后将其打印出来?

另外,如何询问用户是否已经添加足够的项目到列表中?如果用户回答“否”,则会打印出已经存储的项目列表。

谢谢,我是新手所以不怎么懂。


list.append(variable) - devnull
5
如果您是新手,花些时间阅读文档 - devnull
2个回答

18
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

6

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

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]: 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接