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>Jim's answerâcombining a test for <code>askedword in words</code> with a call to <code>words.index(askedword)</code>âis the best and most Pythonic approach in my opinion.</p>

<p>Another variation on the same approach is to use <code>try</code>-<code>except</code>:</p>

<pre><code>try:
    print(words.index(askedword) + 1) 
except ValueError:
    print("word not in sentence")
</code></pre>

<p>However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:</p>

<pre><code>for i, word in enumerate(words):
    if askedword == word :
        print(i+1)
        break
else:    # triggered if the loop runs out without breaking
    print ("word not in sentence")
</code></pre>

<p>In an unusual twist unavailable in most other programming languages, this <code>else</code> binds to the <code>for</code> loop, not to the <code>if</code> statement (that's right, get your editing hands off my indents). <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">See the python.org documentation here.</a></p>

python python-3.x words enumerate sentence