2

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.

1
  • "return each value back to the function the while loop is in…" is exactly what generators are for. See the Iterators and subsequent two sections in the tutorial for an explanation. Commented Dec 3, 2013 at 0:47

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.