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])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…