user2879373
user2879373

Reputation: 73

Return multiple "while" loop results

I have a while loop that returns data to a function.

    while (count < int(pagecount)):
        count = count + 1
        request = requestGet("http://www.site.com/User.aspx?ID={0}&page={1}".format(self.userid, count))
        regexdata = re.findall('REGEX" REGEX="(.*?)"', request)
        return regexdata

I need to know how I can return each value back to the function the while loop is in. Also, to be more specific, the data that I'm returning is actually in a list. So maybe somehow appending the new list to the old list would be a better approach. Either way, I'm lost and I need help.

Thanks.

Upvotes: 2

Views: 1457

Answers (2)

Steve P.
Steve P.

Reputation: 14699

You can use a Generator:

def getRegexData(self):     
    while (count < int(pagecount)):
        count = count + 1
        request = requestGet("http://www.site.com/User.aspx?ID={0}&page={1}".format(
                            self.userid, count))
        yield re.findall('REGEX" REGEX="(.*?)"', request)

Upvotes: 2

user2357112
user2357112

Reputation: 280688

If you want to return a bunch of things, put them in a list and return that:

results = []
while (count < int(pagecount)):
    count = count + 1
    request = requestGet("http://www.site.com/User.aspx?ID={0}&page={1}".format(self.userid, count))
    regexdata = re.findall('REGEX" REGEX="(.*?)"', request)
    results.append(regexdata)
return results

Alternatively, it might be appropriate to yield the results, turning your function into a generator:

while (count < int(pagecount)):
    count = count + 1
    request = requestGet("http://www.site.com/User.aspx?ID={0}&page={1}".format(self.userid, count))
    regexdata = re.findall('REGEX" REGEX="(.*?)"', request)
    yield regexdata

Both of these options let you iterate over the return value to get the elements, but the generator option only lets you do so once. return halts the function immediately, so once your function hits a return, it won't continue on to further loop iterations.

Upvotes: 3

Related Questions