2016-06-09 54 views
-2

我已經寫了一些代碼,可以找到用戶在一個句子中輸入的單詞的位置。但是,在他們輸入詞語後,我需要找到該位置的代碼並打印出來,然後停在那裏。但它不會停止,而是繼續到else語句,如果他們輸入不在句子中的單詞,會發生什麼情況。如果我使用break,它只會打印單詞的第一個位置,如果它在句子中出現多次。我該怎麼辦?我需要停止我的for循環,但休息不會工作

sentence = "ask not what your country can do for you ask what you can do for your country" 
print(sentence) 
keyword = input("Input a keyword from the sentence: ").lower() 
words = sentence.split(' ') 

for i, word in enumerate(words): 
    if keyword == word: 
     print("The position of %s in the sentence is %s" % (keyword,i+1)) 


if keyword != word: 
    keyword2 = input("That was an invalid input. Please enter a word that is in the sentence: ").lower() 
    words = sentence.split(' ') 
    for i, word in enumerate(words): 
     if keyword2 == word: 
      print("The position of %s is %s" % (keyword2,i+1)) 
+0

如果這個詞出現不止一次,你想要的每個單詞的位置? – Doshmajhan

+0

當條件滿足時使用'break'命令。 – user590028

+0

您可能想將其包裝在一個函數中,並在找到時返回值。然後在調用函數時打印返回的值。這樣,您也可以在其他情況下重用它,而無需重新編碼。 :) – codykochmann

回答

1

您可以先獲取所有索引,然後只在沒有匹配索引時才執行第二個函數。

indexes = [i for i, word in enumerate(words) if word == keyword] 
if indexes: 
    for i in indexes: 
     print('The position is {}'.format(i)) 

if not indexes: 
    ... 

你也可以使用一個while循環,這樣就可以只使用一個單一的步驟。

keyword = input("Please enter a word that is in the sentence: ").lower() 
indexes = [i for i, word in enumerate(words) if word == keyword] 
while not indexes: 
    keyword = input("That was an invalid input. Please enter a word that is in the sentence: ").lower() 
    indexes = [i for i, word in enumerate(words) if word == keyword] 

for i in indexes: 
    print('The position is {}'.format(i)) 
+0

感謝您的幫助。我有一個關於while循環的例子,我想了解它是如何解決我的問題的,例如它如何打印兩個位置,然後在打印錯誤消息之前停止。列表理解的目的是什麼? – user6287713

+0

唯一的錯誤條件是如果提供的關鍵字不在單詞列表中。列表理解獲取提供的關鍵字句子中所有匹配索引的列表。如果從列表理解產生的列表爲空,那麼關鍵字不匹配任何單詞,並且您需要重新提示用戶輸入另一個關鍵字。一旦關鍵字與至少一個索引匹配,「索引」將評估爲「真」,並使其突破「while」循環。然後它會打印所有匹配的索引。 –

+0

非常感謝你,你是一個救星! XX – user6287713