Q:

Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string

The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python.
The code that I wrote:
def countLetters(str, ch):
   count=0
   index=0
   for ch in str:
     if ch==str[index]:
       count=count+1
     index=index+1
   print count

when I use this function, it measures the length of the string instead of how many times the character occurs in the string. What did I do wrong? What is the right way to write this code?

A:

You are over-writing your 'ch' variable:
def countLetters(str, ch):
#                      ^ the character you are looking for
    count=0
    index=0
    for ch in str:
#        ^ the string character you are trying to check
        if ch==str[index]:  # ???
            count=count+1
        index=index+1
    print count

(also, it is usually more useful to return the value than to just print it).
The built-in method is str.count:
"aaabb".count("a")  -> 3

How you could rewrite your code:
def countLetters(search_in, search_for):
    count = 0
    for s in search_in:    # iterate by string char, not by index
        if s==search_for:
            count += 1
    return count

and a quick pythonic replacement:
def countLetters(search_in, search_for):
    return sum(1 for s in search_in if s==search_for)

