How do you add input from user into list in Python [closed]

我们两清 提交于 2020-01-01 06:13:40

问题


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

How do I make a list of what the user has said then print it out at the end when they have finished?

Also how do I ask if they have added enough items to the list? And if they say no then it will print out the list of items already stored.

Thanks, I'm new to this so I don't really know.


回答1:


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



回答2:


code below allows user to input items until they press enter key to stop:

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


来源:https://stackoverflow.com/questions/21043387/how-do-you-add-input-from-user-into-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!