Help with this code! Cannot understand what's the bug here. Topic : Python Strings

Write a new function called get_length() that takes a string as an input and

returns the number of characters in that string. Do this by iterating through

the string, don’t cheat and use len()!

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

output = get_length(‘yellow’)
print(output)

I dont understand what’s the bug in this code. It returns as:
TypeError: can only concatenate str (not “int”) to str

This happens when you’re trying to concat a string and integer, rather than casting the int as a string & then concatenating it to a string.
https://stackoverflow.com/questions/51252580/how-to-resolve-typeerror-can-only-concatenate-str-not-int-to-str

Though, there are a few issues here.

Why is “i” outside the function?
You’re using ‘i’ as the temporary variable in the for loop and as the counter of letters in the word paramter. Wouldn’t it be better to call “i” something like “counter” or “sum” (?) (b/c you’re counting the letters in a word and you’re returning the total count

Remove the output = part before the print()
When you call the function, you should be able to pass through any string (as an argument) and the function logic should calculate the count of letters in the string. I hope that makes sense(?)

1 Like

Hey,
Thanks for responding and helping out. As you suggested, I tried with the following syntax,

def get_length(word):

sum = 0

for sum in word:

    sum += 1

    return sum

get_length(‘yellow’)

But I’m still getting the same error.

The return statement is indented inside the for loop. Try removing a single indent from this return statement

I’ve corrected that but the error still remains:
The error shown is;

sum += 1
TypeError: can only concatenate str (not “int”) to str

The general way to write a for loop:

for (temporary variable) in (list variable): (action)

You’re using “sum” as the temp var in the for loop and as the counter of the letters in the string. They are two different types (the link I posted above).

What if you wrote something like this:

def get_length(word):
    sum = 0
    
    for i in word:
        sum += 1
    
    return sum

print(get_length("avocado"))
2 Likes

If you happen to use Google’s Colab, you can search for your error from the notebook itself (or, you could just use Google and search for your error too:

The “thing” that you’re counting is parts of a string. The total of the thing that you’re counting is an integer.

Data types in Python:
https://realpython.com/python-data-types/

1 Like

Hey Lisalisaj, thank you so much for that! I’m still trying to get the hang of python syntax and so tend to miss out on small things. Thanks again

1 Like