How to the character count of a string, compared to the string count

Python: Iterating through Strings activity

def get_length(string):
  counter = 0
  for letter in string:
    counter = counter + 1
    return counter


print(get_length("Toll"))

For some reason, I am not understanding how to iterate through the string for the character count. Based on my understanding, a counter needs to be created, to store the iterated character, and will add one to the counter. However, the only output that comes is a ‘1’ representing the string given to the function. Any and all help will be appreciated.

Thank you in advance

So the issue with the code snippet you shared is that you’re using return inside of a loop. Because return stops the function from running as well as returning the value, the loop only runs once before hitting the return and therefore stopping the function, which means counter can never be higher than 1, regardless of the inputted value. You only want to return the counter after the loop has executing, so that you are returning the final value.

2 Likes