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

Learning the inner workings of a Python Function.

Hello ALL.

I am currently learning Python Functions, reading Tracebacks and using the debugger in VSCode.

Here is some code I put together but I get an recursion depth error.

def preloader_goal(g):
    goal_met = preloader_goal
    print(goal_met(f"Thats great you got all {preloader_goal} of your boxes loaded."))
preloader_goal(20)

The error I get is: [Previous line repeated 995 more time] RecursionError: maximum recursion depth exceeded while getting the str of an object.

I was trying to get a custom output of goal_met when preloader_goal was called. What am I not seeing?

Here is the newest variation of what was wanting to do it works, but i am not sure why its working.

goal = 20

def preloader_goal(goal)
    if goal == 20:
        return("You have reached the go goal of 20.")
    else:
        return("You have not reached the goal of 20.")

print(preloader_goal(goal))

So I guess what I am asking now is ... is this current variation an actual version of the previous code sample or is it just a whole other way of writing the code?

1 Answer

Steven Parker
Steven Parker
231,248 Points

The first example is infinitely recursive, as the function calls itself unconditionally (after giving itself a new name of "goal_met"). Recursive functions must always have a test for an exit condition to avoid exceeding system limits.

The second example just performs a simple test and returns one of two options. It doesn't call any other functions (including itself, so no recursion).