searching the number of times the letter s appears in the word Mississippi

93 Views Asked by At

I am trying to find the number of times the letter "s" appears in the word "Mississippi". Why doesn't my code work? I should get an output of 4.

def find(word,letter):
    index=0
    while index <len(word):
        if word[index]==letter:
            return index
            index=index
print (index)


find("mississippi", "s")
1

There are 1 best solutions below

2
ItsMe On

I think you didn't added the counter, and the index isn't increasing. I reworked your code:

def find(word,letter):
    index=0
    times=0 #added variable to hold number of times

    while index <len(word):
       
        if word[index]==letter:
            times+=1 #this will increase the counter when the letter is matched
        index += 1 #this will increase the index
    print (times)


find("mississippi", "s")