0

I am trying to count the numbers of "e" in a word without using count.(). I made a definition but it outputs this:

0
1
1
2

How do I make it output just 2 ?

def letter_e(word):
    count = 0
    for letter in word:
        if letter == "e" :
            count += 1 
        print(count)

letter_e("fefe")
techaina
  • 1
  • 1
  • 6
    Don't print inside the loop? Better yet don't print inside the _function_, return the count so you can reuse the functionality elsewhere. – jonrsharpe Jan 24 '22 at 22:47
  • You can also do `def letter_e(word): return sum(sym == 'e' for sym in word)`, it doesn't use `.count()` method and is shorter and faster. – STerliakov Jan 24 '22 at 22:57
  • Does this answer your question? [Count the number of occurrences of a character in a string](https://stackoverflow.com/questions/1155617/count-the-number-of-occurrences-of-a-character-in-a-string) – tgpz Jan 24 '22 at 22:57
  • @jonrsharpe Hello! Thanks for your help. I switched print with return, but the value that it outputs is now 0 – techaina Jan 24 '22 at 23:03
  • I guess you're returning inside the loop then. That doesn't make sense, a function can only return once and you don't want to return on the first character. – jonrsharpe Jan 24 '22 at 23:03
  • @jonrsharp it works ! Thank you so much :) – techaina Jan 24 '22 at 23:04
  • You could use split: `return len(word.split('e'))-1` – Alain T. Jan 25 '22 at 00:24
  • Or sum: `return sum(c=='e' for c in word)` – Alain T. Jan 25 '22 at 00:25

1 Answers1

1

As your print statement is within your for loop, every time an "e" is found within the string your count variable is printed.

If you only want to print the final answer, print your count variable outside your for loop.

The code would look like this:

def letter_e(word):
    count = 0
    for letter in word:
        if letter == "e" :
            count += 1 
    print(count)

letter_e("fefe")
AJD
  • 66
  • 6