2016-10-28 19 views
-1

私は、ユーザーの買い物リストを作成するプログラムを作っています。 は、 'end'と入力してからリストを印刷するまで、繰り返しユーザーにアイテムを尋ねる必要があります。ユーザーが既にアイテムを追加している場合は、次回に無視する必要があります。私は重複を無視すべき最後の部分で問題が発生しました。私はまた、 '続行'を使用する必要がありますが、私のコードにどのように実装するのか分かりません。同じ入力を2度入力しないでください

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) 
+0

あなたは...あなたは項目がリストにあるかどうかを確認するために近くに必要だということは、重複の世話をし、あなたは、彼らのためにチェックするだけでshopping_list.add(item)を使用する必要はありません(とshopping_list = set()で初期化) *前にそれを追加してから 'continue'をその' if'文に追加してください... –

+0

hmm私はまだそれを得ることはできません。 'item in item:'はよく書かれたコードですか? – user3077730

+0

私はあなたが 'item if item in item 'の代わりに' if item in shoppingListVar'を意味したと思う。 –

答えて

0

を変更する必要があり、3種類の予想される条件

に対処するために、あなたのコード内であれば、elifの - 他の構造を使用した方が良いだろう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) 

最初のリストに新しい項目を追加する前に、センチネル値(「終了」)のためにこのコードチェックは、それがその中に存在しない場合。

ショッピングリストの順序が問題でない場合、またはとにかく並べ替える場合は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) 
+0

私はその練習用のリストを使用しなければなりませんでしたが、心に留めておきます。 – user3077730

+0

@ user3077730:十分に公正です。 – mhawke

+0

@ user3077730: 'continue'を使用する必要がある場合は、重複エントリを検出するたびに追加することができます。更新された回答をご覧ください。 – mhawke

0

また、あなたは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) 
+0

ohh私は' shoppingListVar: 'itemをifにしようとしましたが、if-elif-else構造を持っていました。作業。 'continue'ステートメントを投げる機会はありますか?どのように動作するのかわかりません – user3077730

関連する問題