The most common answer is:
def count_occurrences(word, character):
counter = 0
for checker in word:
if checker == character:
counter += 1
return counter # Make sure to return the count, not print it
# Correct the call to print the return value of the function
print(count_occurrences("banana", "a"))
This code defines a function count_occurrences
that iterates over each character in word
and increments a counter each time it matches the specified character
. Finally, it returns the value of counter
.
The corrected print statement outside the function call ensures that the result is displayed to the user, showing how many times “a” appears in “banana”, which is 3.