Write a function that finds the number of occurrences of a specified character in the string using the following header: def count(s, ch): For example, count("Welcome", 'e') returns 2. The str class has the count method. Implement your function without using the count method. Write a test program that reads a string and a character and displays the number of occurrences of the character in the string.

Respuesta :

Answer:

def count(userInput, character):

   occurrences = 0

   for character_in_string in userInput:

       if(character == character_in_string):

           occurrences += 1

   return occurrences

userInput = input("Enter string: ")

character = input("Enter character: ")[0]

print(count(userInput, character))

Explanation:

  • Define a count function that takes in the userInput as a string and character parameters.
  • Loop through the userInput and check whether selected character is equal to the character found in the string.
  • Increase the counter of occurrences by 1 if the condition is true and then return the occurrences.
  • Take the userInput and character as input from the user.
  • Finally display the results by calling the count function.
fichoh

Using Python 3, the function returns the number of occuences of a letter in a given phrase. The program gives thus :

def count(inp, character):

#initialize function

num = 0

#initialize the number of occuences

for character_in_string in inp:

if(character == character_in_string):

num += 1

#add the number of occurrences

return num

inp = input("Enter string: ")

character = input("Enter character: ")[0]

print(count(inp, character))

A sample run of the program is attached.

Learn more : https://brainly.com/question/16999822

Ver imagen fichoh