【问题标题】:How do you add input from user into list in Python [closed]如何将用户的输入添加到 Python 的列表中 [关闭]
【发布时间】:2014-01-10 11:39:10
【问题描述】:
print ('This is your Shopping List')          
firstItem = input('Enter 1st item: ')         
print (firstItem)             
secondItem = input('Enter 2nd item: ')           
print (secondItem)  

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

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

谢谢,我是新手,所以我不太清楚。

【问题讨论】:

  • list.append(variable)
  • 如果您是新手,请花点时间阅读documentation

标签: python list shopping


【解决方案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】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多