相同的输入两次不输入两次

时间:2016-10-28 09:55:38

标签: python python-3.x

我正在制作为用户构建购物清单的程序。这应该 反复询问用户的项目,直到他们进入'结束'然后它应该打印列表。如果用户已经添加了项目,则下次应该忽略该项目。我遇到了问题,最后一部分应该忽略重复。我也需要使用'继续'但不知道如何实现我的代码。

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)

2 个答案:

答案 0 :(得分:0)

您最好在代码中使用if-elif-else结构来处理3种不同的预期条件

您还需要将if item in item:更改为if item in shoppingListVar:

shoppingListVar = []
while True:
    item = input("Enter your Item to the List: ")
    if item in shoppingListVar:
        print("you already got this item in the list")
    elif item == "end":
        break
    else:
        shoppingListVar.append(item)
print ("The following elements are in your shopping list:")
print (shoppingListVar)

答案 1 :(得分:0)

应为if item in shoppingListVar:

shoppingListVar = []
while True:
    item = input("Enter your Item to the List: ")
    if item == "end":
        break

    if item in shoppingListVar:
        print("you already got this item in the list")
        continue

    shoppingListVar.append(item)

print ("The following elements are in your shopping list:")
print (shoppingListVar)

此代码在将新项目附加到列表之前首先检查sentinel值('end'),如果它尚未存在。

如果购物清单的顺序无关紧要,或者您要对其进行排序,则可以使用set代替list。这将照顾重复项,您无需检查它们,只需使用shopping_list.add(item)(并使用shopping_list = set()进行初始化)

shopping_list = set()
while True:
    item = input("Enter your Item to the List: ")
    if item == "end":
        break
    shopping_list.add(item)

print("The following elements are in your shopping list:")
print(shopping_list)