Python newb here. I m trying to count the number of letter "a"s in a given string. Code is below. It keeps returning 1 instead 3 in string "banana". Any input appreciated.
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
count += 1
return count
print count_letters('banana','a')
Best Answer
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:
Danben gave this corrected version:
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: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:The next one filters out all the characters that don't match
char
, and counts how many are left: