I am trying to count the number of times 'e' appears in a word.
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
It seems to work fine except when the word ends with an 'e'. It will count that 'e' twice. I have no idea why. Any help?
I know my code may be sloppy, I'm a beginner! I'm just trying to figure out the logic behind what's happening.
As others mention, you can implement the test with a simple word.count('e')
. Unless you're doing this as a simple exercise, this is far better than trying to reinvent the wheel.
The problem with your code is that it counts the last character twice because you are testing index -1
at the end, which in Python returns the last character in the string. Fix it by changing while letters >= 0
to while letters > 0
.
There are other ways you can tidy up your code (assuming this is an exercise in learning):
for
loop. This is far more concise and easier to read than using a while
loop and maintaining your own counter variable. As you've already seen here, adding complexity results in bugs. Keep it simple.+=
operator, which for integers adds the amount to a variable. It's more concise than count = count + 1
.char='e'
in the parameter list when you have an obvious default.has_no_e()
makes the reader think the code checks to see if the code has no e, but what it actually does is counts the occurrences of e.Putting this all together we get:
def count_letter(word, char='e'):
count = 0
for c in word:
if c == char:
count += 1
return count
Some tests:
>>> count_letter('tee')
2
>>> count_letter('tee', 't')
1
>>> count_letter('tee', 'f')
0
>>> count_letter('wh' + 'e'*100)
100