alibongo alibongo - 9 days ago 6
Python Question

Else statement not working with my if statement

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

for i, word in enumerate(words):
if keyword == word:
print(i+1)
else:
print("the word,",keyword,",is not in the sentence")


Without the else statement the place where the word is in the sentence will be printed, however, once I added the else statement was added, even if the word is in the sentence "the word,",keyword,",is not in the sentence" is printed.

Answer

The else would kick in for every word that is not the keyword, resulting in many 'failures'.

Use a for-else loop with breaking condition, so your program will show the failing output only if no word matches the keyword:

for i, word in enumerate(words):
    if keyword == word:
        print("found at index", i+1)
        break
else:
    print("the word '", keyword, "' is not in the sentence")
Comments