我正在制作一个为用户建立购物清单的程序。它应该 反复要求用户输入项目,直到他们输入“end”,然后它应该打印列表。如果用户已经添加了一个项目,下次应该忽略它。我在最后一部分遇到了问题,它应该忽略重复。我也被要求使用'continue',但不知道如何实现我的代码。在
shoppingListVar = []
while True:
item = input("Enter your Item to the List: ")
shoppingListVar.append(item)
if item in item:
print("you already got this item in the list")
if item == "end":
break
print ("The following elements are in your shopping list:")
print (shoppingListVar)
最好在代码中使用if-elif-else结构来处理3种不同的预期条件
您还需要将
if item in item:
更改为if item in shoppingListVar:
它应该是
if item in shoppingListVar:
。在此代码首先检查sentinel值('end'),然后再将新项附加到列表中(如果列表中不存在)。在
如果购物清单的顺序无关紧要,或者您要对其进行排序,那么可以使用
^{pr2}$set
而不是list
。这样可以处理重复项,而不需要检查它们,只需使用shopping_list.add(item)
(并用shopping_list = set()
初始化)相关问题 更多 >
编程相关推荐