同一输入两次不能输入twi

2024-09-29 22:00:46 发布

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

我正在制作一个为用户建立购物清单的程序。它应该 反复要求用户输入项目,直到他们输入“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)

Tags: the项目用户in程序列表yourif
2条回答

最好在代码中使用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)

它应该是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()初始化)

^{pr2}$

相关问题 更多 >

    热门问题