Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

I've been giving over this function for a day and I can't seem to work out how it is working. Would someone kindly help?

Would someone help a newbie explain what is going on in detail? Thanks!!

def recursive(depth):
    depth+=1
    while (depth < 5):
        ret = recursive(depth)
    return depth

ret = recursive(0)
print("the recursive depth is ", ret)

1 Answer

it's a recursive function that calls itself in the body. this creates what is sometimes called a stack of recursive function calls. the stack ends when what is called the base case is reached, and then the function moves back up through the stack and returns the result. there is nothing wrong with this, a common example is computing factorials or fibonacci numbers, but this particular function does not have a base case and therefore causes an infinite loop. the depth variable counts up to 5 and creates a stack of depth 5, and at 5 it skips the while loop and returns 5, but the next step is to move back up through the stack. in the previous level, depth is still 4. 4 is less than 5, so it enters the while loop, the function is called on 4, 1 is added to 4 to make 5, 5 skips the while loop and is returned, and on and on it goes.

A ha! Thank you so much for the clarification. That one has been bugging me.