118k views
0 votes
Exercise 8-3 Encapsulate

fruit = "banana"
count = 0
for char in fruit:
if char == "a":
count += 1
print(count)


This code takes the word "banana" and counts the number of "a"s. Modify this code so that it will count any letter the user wants in a string that they input. For example, if the user entered "How now brown cow" as the string, and asked to count the w's, the program would say 4.

Put the code in a function that takes two parameters-- the text and the letter to be searched for. Your header will look like def count_letters(p, let) This function will return the number of occurrences of the letter.
Use a main() function to get the phrase and the letter from the user and pass them to the count_letters(p,let) function. Store the returned letter count in a variable. Print "there are x occurrences of y in thephrase" in this function.
Screen capture of input box to enter numbeer 1

1 Answer

5 votes

Answer:

python

Step-by-step explanation:

def count_letters(p, let):

count = 0

for char in p:

if char == let:

count += 1

print(f"There are {count} occurrences of {let} in the phrase {p}")

def main():

the_phrase = input("What phrase to analyze?\\")

the_letter = input("What letter to count?\\")

count_letters(the_phrase, the_letter)

main()

User Stephen Docy
by
5.0k points