Recursion Depth Reached?

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

https://www.codecademy.com/courses/learn-python-3/lessons/introduction-to-strings/exercises/iterating-through-strings
Hello all! Whenever I’m trying to work through this exercise I am getting a “recursion depth reached” error. When I compare my code to the experience programmer I am still getting issues. Anyone have an idea on what this could be?

counter = 0
def get_length(word):
  #counter = 0
  for word in get_length(word):
    counter += 1 
    return counter

Welcome to the forums!

Because you are calling get_length(word) from inside the condition of the for loop you have created an infinite loop, the function will keep calling itself repeatedly until it throws the error you encountered (which will happen after 999 iterations) and the rest of the code in the function will never run. Having functions call themselves is a concept called recursion, which can be very useful but it’s not what you want in this situation. If you wanted to run the loop once for every letter in the word you would want to do something along the lines of for letter in word instead.

Also, you have return counter inside of the loop. In almost all situations you want to avoid this as a return statement exits the function when it is executed, which means the loop is only capable of running once before it hits the return statement and stops leading to counter having a maximum possible value of 1.
You only want to return the value from counter after the loop has finished.

2 Likes