Reputation: 53
I want to make a while
loop that runs indefinitely until a condition is true.
The problem is when the condition isn't true the loop only runs for around two minutes and then breaks return the following error:
RecursionError: maximum recursion depth exceeded in comparison
Here's the entire code:
def request():
s = requests.Session
r = s.get(url)
return r
def data(r):
soup = BeautifulSoup(r.text, 'lxml')
list = soup.select('.class')
return list
def loop(list):
n = 10
while True:
len(list) != n
if len(list) == n:
print('Lorem ipsum')
main()
else:
return len(list)
def main():
r = request()
list = data(r)
len(list) = loop(list)
if __name__ == "__main__":
main()
Upvotes: 0
Views: 862
Reputation: 930
Well you are calling the function main()
which then runs the script in main()
which is probably the code you posted above. Therefore you created a recursional function which never returns anything. So to avoid going on forever python has a recursion depth limit which the throws an error.
I am not sure what you are trying to achieve here, but I would think calling main()
like that is a bad idea. If you are only trying to loop through your while loop without leaving it you do not need to call main again as pythoon will keep looping through it until the condition is not met anymore. Please have a look at the documentation on how a while loop works.
Please take a look at Recursion.
Upvotes: 2
Reputation: 5478
Function is only finished with an explicit return
or when it gets to the end of the function's code (implicit return None
).
When you call main
, you don't finish loop
- it gets put on the call stack. It gets back to that loop
(exactly after the main()
line) when main()
returns (finishes).
However, in your case, main
is probably constructed in such a way that doesn't return and call loop
again. Thus putting main
on the call stack as well.
Then loop
calls main
again, then main
calls loop
... none of them return, thus the call stack grows and grows until there's no more memory... or until it hits the safeguard max stack size (recursion depth) like yours did.
loop
never gets into else
because list is defined here, thus always being the same size. That means the while
in loop
never breaks. - The list is a local variable, no calls to other functions will modify it because you don't pass the object.
Upvotes: 1
Reputation: 460
RecursionError
is raised when there's a cycle. RecursionError is thrown when there are too many function calls on the stack., you are looping an infinite amount of your main() function
Upvotes: 0