[FEEDBACK] Is this script efficient...is there a better way?

Sean 'Shaleh' Perry shalehperry at attbi.com
Thu Sep 12 01:31:20 EDT 2002


On Wednesday 11 September 2002 18:09, Bob X wrote:
> > 2) do you expect to find more than one keyword in a particular line?  If
> > not you could save some iterations by stopping the inner line.find() loop
> > as soon as one item is found.
>
> I could but it doesn't matter after the first on a line. How would I
> stop it?
>

use 'break'

for i in range(1,20):
    if i == 6:
        break
    print i

and you get:
1
2
3
4
5

so your code becomes:

for line in inFile.readlines():
     for badword in kw:
         if line.find(badword) > -1:
             result = '%s %s' % (badword, line)
             print result            # Print the result
             outFile.write(result)   # Write the result
             break                   # only need one keyword on a line

there is also the keyword 'continue' which says "I am done with this loop 
iteration, go back to the top of the loop".

for i in range(1,20):
    if (i % 2) == 0:
        continue
    print i

this loop will only print the odd numbers.




More information about the Python-list mailing list