2017-02-09 4 views
0

このコードを実行すると、「検索に失敗しました」というメッセージが表示されます。私はそれにループがあることを知っていますが、文中の単語の位置がすべて見つかったらコードをループさせる方法を理解できません。forループとif文が間違ったメッセージを表示する

sentence= "the hat ran away from the cat" 
    print(sentence) 
    word_to_find= input("write word from sentence") 
    senLow= sentence.lower() 
    word= word_to_find.lower() 
    senList= senLow.split() 

    for pos in range(len(senList)): 
     if word== senList[pos]: 
      print(word, "found in position:", pos+1) 

    else : 
     print ("search unsuccessful") 
+7

ここに該当するコードをテキストとして入力してください。 = – Carcigenicate

+0

文 プリント(文) word_to_find =入力( "文から書き込みワード") senLow = sentence.lower() 単語= word_to_find.lower() senList = senLow "帽子は離れて猫から走りました"。スプリット()の範囲内のPOS(LEN(senList))のための : ならワード== senList [POS]: プリント(単語、 "位置に見出される:"、POS + 1)他 : プリント(」 seacrh unsuccessful ") –

+2

あなたの' else'は 'for'文に適用され、' if'文は適用されません。ループから脱出しない限り、常に実行されます。 –

答えて

0

これを試してみてください:

sentence = "the hat ran away from the cat" 
print(sentence) 
word_to_find = input("write word from sentence") 
senLow = sentence.lower() 
word = word_to_find.lower() 
senList = senLow.split() 
found = False 
for pos in range(len(senList)): 
    if word == senList[pos]: 
     print(word, "found in position:", pos+1) 
     found = True 

if not found: 
    print ("seacrh unsuccessful") 

私がそうでなければ「seacrh失敗した」、単語が文の中で発生した場合にtrueに設定されます「が見つかり」フラグを追加し、印刷されます。

+0

これはおそらく望ましくないそれぞれの単語をチェックした後、検索に失敗したものを印刷します。 – Mark

+0

ええ、そうです。だから、フラグが良いアイデアかもしれません。 – magdgar

+0

この解決策を編集しました。今それは良いでしょう。 – magdgar

関連する問題