Print "Match Found" for each line the search is in and "Match not Found" if the search isnt in the whole file
<p>I want to print "Match Found" and the line that the match is in if the search is in a line in the file. Note - the match can be in more than one line and if so it should print every line the match is in. I have got this part working but i want to print "Match Not Found" once if the search isn't in the whole file. So far whatever I have tried either prints "Match Not Found" for every line the search isnt in or it prints "Match not Found" after printing the lines the search is in.</p>

<pre><code>f = open("cars.txt", "r+")
search = input("What do you want to search for? ")
for line_split in f:
    if search in line_split:
        print ("You searched for %s." % search)
        print ("Match Found.")
        print (line_split)
        print ("--------------------")
else:
        print ("You searched for %s" % search)
        print ("Match Not Found.")
        print ("--------------------")
f.close
</code></pre>

<p>First of all, I think you are misunderstanding the way of how "else" statement after the for loop works. It will execute only if the for loop wasn't break.</p>

<pre><code>n = 10
for idx in range(n):
    if idx &gt; 11:
       print('Yey, we reached {}'.format(idx))
       break
else:
    print('Damn, we almost had it!')
</code></pre>

<p>This code will result in:</p>

<pre><code>Damn, we almost had it!
</code></pre>

<p>But if we change n = 20, we will get:</p>

<pre><code>Yey, we reached 12
</code></pre>

<p>I see no "break" in your code, so it's either an intendation error, or you just didn't realized that.</p>

<p>I will not post the next way of solving the problem, when it was already been told. I just wanted u to know the difference in using "else" statement outside the for loop. </p>

python python-3.x