I use the two functions below to search a string for a target character and return the count of times the character occurs.
def find(word, letter, start):
index = start
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
def counter(word, target):
count = 0
start = 0
while start < len(word):
result = find(word, target, start)
if result == -1:
print(count)
else:
count = count + 1
start = result + 1
find(word, target, start)
print(count)
Searching like this returns the correct counts, but the while loop does not stop in situations where the character occurs once or not at all. What's the correct way to terminate the while loop?
counter("Tyrannosaurus","y")