Search code examples
pythoncountletter

Count letters in a word in python debug


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.


Solution

  • 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):

    • Python provides a nice way of iterating over a string using a 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.
    • Most languages provide a += operator, which for integers adds the amount to a variable. It's more concise than count = count + 1.
    • Use a parameter to define which character you're counting to make it more flexible. Define a default argument for using char='e' in the parameter list when you have an obvious default.
    • Choose a more appropriate name for the function. The name 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