Can't get program to print "not in sentence" when word not in sentence
<p>I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:</p>

<pre><code>sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")

for i, word in enumerate(words):
     if askedword == word :
          print(i+1)
    #elif keyword != words :
         #print ("this not")
</code></pre>

<p>However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"</p>

<p>Lists are sequences, as such you can use <a href="https://docs.python.org/3.5/library/stdtypes.html#common-sequence-operations" rel="nofollow">the <code>in</code> operation</a> on them to test for membership in the <code>words</code> list. If inside, find the position inside the sentence with <code>words.index</code>:</p>

<pre><code>sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")

if askedword in words:
    print('Position of word: ', words.index(askedword))
else:
    print("Word is not in the given sentence.")
</code></pre>

<p>With sample input:</p>

<pre><code>enter sentence: hello world

enter word to locate position: world
Position of word: 1
</code></pre>

<p>and, a false case:</p>

<pre><code>enter sentence: hello world

enter word to locate position: worldz
Word is not in the given sentence.
</code></pre>

<p>If you're looking to check against multiple matches then a list-comprehension with <code>enumerate</code> is the way to go:</p>

<pre><code>r = [i for i, j in enumerate(words, start=1) if j == askedword]
</code></pre>

<p>Then check on whether the list is empty or not and print accordingly:</p>

<pre><code>if r:
    print("Positions of word:", *r)
else:
    print("Word is not in the given sentence.")
</code></pre>

python python-3.x words enumerate sentence