martinbshp martinbshp - 6 months ago 9
Python Question

Stop endless while True loop

The following program causes an endless loop. How do I stop the while from continuing once I've read in all the links? Thank you.

def findAllURLs():

with open('manylinks.html', 'r') as f:
data = f.read()
start = data.find('href')
while(True):
begin = data.find('"',start)
end = data.find('"',begin+1)
print data[begin+1:end]
start = data.find('href',end + 1)


if __name__ == "__main__":
findAllURLs()

3kt 3kt
Answer

You should modify your code this way :

def findAllURLs():

    with open('manylinks.html', 'r') as f:
        data = f.read()
        start = data.find('href')
        while(start != -1):
            begin = data.find('"',start)
            end = data.find('"',begin+1)
            print data[begin+1:end]
            start = data.find('href',end + 1)


if __name__ == "__main__":
    findAllURLs()

Indeed, find will return -1 when it can't find any additional matches, and hence end the while loop.

Comments