Write a function called count_occurrences that takes two strings. The second string should only be one character long. The function should return how many times the second string occurs in the first string.


You will need:


A function declaration for the function count_occurrences, with parameters.

A for loop.

An if statement.

A return statement.

Ask the user to input both strings (first the word, and then the letter). Then enter the two strings as parameters to your function.



the code I have is

Write a function called countoccurrences that takes two strings The second string should only be one character long The function should return how many times th class=

Respuesta :

Answer:

you are doing 1 string so you don't need all of the loops you had. string 2 is already char you don't need to change anything about it. you only need 1 loop.

def count_occurrences(string1, string2):

   count = 0

   for char in string1:

       if char is string2:

           count = count + 1

   return count

first_str = input("Enter the first string:")

second_str = input("Enter the second string (one character long) : ")

occurrence = count_occurrences(first_str, second_str)

print(second_str + " occurs " + str(occurrence) + " time in " + first_str)

ACCESS MORE