在lis中追加用户输入

2024-04-25 17:53:32 发布

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

我在第二个和第三个if语句中遇到了问题。它似乎注册了输入,但并没有将其添加到列表中。如果按2添加产品,按1列出产品,您可以观察到我所说的问题。你会注意到什么都没有悲伤地出现。好像列表还是空的,但我给了它一个项目。有什么办法解决吗?你知道吗

hell_is_not_frozen = True
while hell_is_not_frozen:

  #menu 
  def menu():
    tab = ' '
    print (40*'=')
    print (8*tab + 'Shopping list app v1\n')
    print (12*tab + 'MAIN MENU \n\n')



  #options
  def options():
    print('[1] View products in list \n'
          '[2] Add a product to list \n'    
          '[3] Remove a product from list :c \n'
          '[4] Exit program\n\n'
          'To choose an option type coresponding number:')

  #calling feds (defs backwords) nice joke isn't it ?  :)
  menu()
  options()

  #Making sure input is int type
  #TODO Implement anit-other-character system 
  numberInt = raw_input()
  number = int(numberInt)

  #Core of this app
  shoppingList = []



  #checking wich option was picked  
  if number == 1:
    if len(shoppingList) == 0:
      print('\nYour shopping list doesn\'t seem to contain any products')
    print ('\n')
    print('\n'.join(shoppingList)) 
    print ('\n\n\n')

  if number == 2:
    #taking a name of beloved product user would like to add
    productAddStr = raw_input("\nWhat product would you want to add in?\n")
    productAdd = str(productAddStr)
    shoppingList.append(productAdd)
    print(shoppingList)

  if number == 3:
    #taking a name of beloved product user would like to Remove
    productRmStr = raw_input("\nWhat product would you want to add in?\n")
    productRm = str(productRmStr)
    shoppingList.remove(productRm)

  if number == 4:
    #Exiting
    print('\nSee you next time :D')
    hell_is_not_frozen = False

Tags: tonumberinputifisnotproductshoppinglist
1条回答
网友
1楼 · 发布于 2024-04-25 17:53:32

我可以看到两个问题:

首先,在while循环中重新初始化shoppingList = [],这基本上意味着每次运行都会忽略其中的值。将此初始化移出while循环。你知道吗

hell_is_not_frozen = True
#Core of this app
shoppingList = []
while hell_is_not_frozen:
    # remaining code goes here

第二个是这个if块

if number == 3:
    #taking a name of beloved product user would like to Remove
    productRmStr = raw_input("\nWhat product would you want to add in?\n")
    productRm = str(productRmStr)
    shoppingList.remove(productRm)

在这里,您尝试删除productRm而不检查它是否存在于列表中,这将抛出一个ValueError。我建议您检查产品是否存在,然后尝试删除它,或者在一次尝试中包含.remove,除了:

if number == 3:
    #taking a name of beloved product user would like to Remove
    productRmStr = raw_input("\nWhat product would you want to add in?\n")
    productRm = str(productRmStr)
    try:
        shoppingList.remove(productRm)
    except ValueError:
        pass

相关问题 更多 >