user3077730 user3077730 - 1 month ago 8
Python Question

same input twice not to be entered twice

I am making program that builds a shopping list for a user. It should
repeatedly ask the user for items until they enter 'end' and then it should print the list. If the user has already added an item it should be ignored the next time. I got the problem with the last part where it should ignore the duplicate.I am also required use 'continue' but no idea how to implement to my code.

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)

Answer

It should be 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)

This code checks for the sentinel value ('end') first before appending the new item to the list, if it is not already present therein.

If the order of the shopping list does not matter, or you are going to sort it anyway, you could use a set instead of a list. That will take care of duplicates and you won't need to check for them, just use shopping_list.add(item) (and initialise with 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)