我遇到第2和第3 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
答案 0 :(得分:0)
我可以看到两个问题:
1,您在shoppingList = []
循环中重新初始化while
,这基本上意味着每次运行都会忽略其中的值。将此初始化移出while循环。
hell_is_not_frozen = True
#Core of this app
shoppingList = []
while hell_is_not_frozen:
# remaining code goes here
第二个是if if block
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
。我建议您检查产品是否存在,然后尝试将其删除,或者在try-except中包含.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