Letter Count on a string
One problem is that you are using count
to refer both to the position in the word that you are checking, and the number of char
you have seen, and you are using char
to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.
Also, move the return
statement outside the loop; otherwise you will always return after checking the first character.
Finally, you only need one loop to iterate over the string. Get rid of the outer while
loop and you will not need to track the position in the string.
Taking these suggestions, your code would look like this:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
The other answers show what's wrong with your code. But there's also a built-in way to do this, if you weren't just doing this for an exercise:
>>> 'banana'.count('a')
3
Danben gave this corrected version:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
Here are some other ways to do it, hopefully they will teach you more about Python!
Similar, but shorter for
loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:
def count_letters(word, char):
count = 0
for c in word:
count += (char == c)
return count
Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn't match char
and 1 if it does, and then sums them:
def count_letters(word, char):
return sum(char == c for c in word)
The next one filters out all the characters that don't match char
, and counts how many are left:
def count_letters(word, char):
return len([c for c in word if c == char])