Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively

When it is required to check the number of times a given letter occurs in a string using recursion, a method can be defined, and an ‘if’ condition can be used.

The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.


Below is a demonstration for the same −

 Live Demo

def check_frequency(my_str,my_ch):
   if not my_str:
      return 0
   elif my_str[0]==my_ch:
      return 1+check_frequency(my_str[1:],my_ch)
      return check_frequency(my_str[1:],my_ch)
my_string = input("Enter the string :")
my_char = input("Enter the character that needs to be checked :")
print("The frequency of " + str(my_char) + " is :")


Enter the string :jaanea
Enter the character that needs to be checked :a
The frequency of a is :


  • A method named ‘check_frequency’ is defined that takes a string and a character as parameters.
  • It checks to see if the characters in a string match the character passed to the method.
  • If they do, it is returned.
  • Else the method is called recursively on all characters of the string.
  • The string and the character are taken as user inputs.
  • The method is called by passing these values as parameters.
  • The output is dislayed on the console.