将项目添加到列表中后,下次添加其他项目时,该项目将被删除。
food_choice = str(input("Do you want to add an item, remove an item or search for a recipes? "))
food = []
if food_choice in ["Add", "add"]:
food_to_add = str(input("Which item would you like to add? "))
food.append(food_to_add)
print(food_to_add, "has been addded to your fridge list.")
print(food)
答案 0 :(得分:1)
您需要初始化列表,然后重复添加项目。实现此目的的自然方法是将您的逻辑包装在while
循环中,并添加一个结束循环的选项,例如关键字“结束”。
否则,就像您的代码中一样,food = []
每次都会初始化一个新的空列表。
food = []
while True:
food_choice = str(input("Do you want to add, remove, search, or end? "))
if food_choice.lower() == 'end':
break
if food_choice.lower() == 'add':
food_to_add = str(input("Which item would you like to add? "))
food.append(food_to_add)
print(food_to_add, "has been addded to your fridge list.")
print(food)
用法示例:
Do you want to add, remove, search, or end? add
Which item would you like to add? banana
banana has been addded to your fridge list.
['banana']
Do you want to add, remove, search, or end? add
Which item would you like to add? orange
orange has been addded to your fridge list.
['banana', 'orange']
Do you want to add, remove, search, or end? end