91.9k views
1 vote
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. Ex: If the input is:

User Vianca
by
5.7k points

1 Answer

4 votes

Answer:

The program written in python is as follows

def countchr(phrase, char):

count = 0

for i in range(len(phrase)):

if phrase[i] == char:

count = count + 1

return count

phrase = input("Enter a Phrase: ")

char = input("Enter a character: ")

print("Occurence: ",countchr(phrase,char))

Step-by-step explanation:

To answer this question, I made use of function

This line defines function countchr

def countchr(phrase, char):

This line initializes count to 0

count = 0

This line iterates through each character of input phrase

for i in range(len(phrase)):

This line checks if current character equals input character

if phrase[i] == char:

The count variable is incremented, if the above condition is true

count = count + 1

The total number of occurrence is returned using this line

return count

The main method starts here; This line prompts user for phrase

phrase = input("Enter a Phrase: ")

This line prompts user for a character

char = input("Enter a character: ")

This line prints the number of occurrence of the input charcater in the input phrase

print("Occurence: ",countchr(phrase,char))

User Lowleetak
by
5.9k points