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

2024-10-05 15:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何列出用户所说的内容,并在用户完成后打印出来?

另外,我该如何询问他们是否在列表中添加了足够的项目?如果他们说不,它就会打印出已经储存的物品清单。

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


Tags: 项目用户内容列表inputyouristhis
2条回答

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

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

相关问题 更多 >