Python Program to Check Whether a String is a Palindrome or not Using Recursion

PythonServer Side ProgrammingProgramming

When it is required to check if a string is a palindrome or not using recursion technique, simple indexing and a user defined function, along with recutsion is used.

Palindromes are those strings or values which when read from left to right and right to left have the same characters in their respective indices.

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_palindrome(my_str):
   if len(my_str) < 1:
      return True
      if my_str[0] == my_str[-1]:
         return check_palindrome(my_str[1:-1])
         return False
my_string = str(input("Enter the string :"))
print("The string is ")
   print("The string is a palindrome")
   print("The string isn't a palindrome")


Enter the string : MalaM
The string is
The string is a palindrome


  • A method named ‘check_palindrome’ takes a string as a parameter.
  • If the size of the string is less than one, ‘True’ is returned as output.
  • Otherwise, the last element in the string is checked to see if it matches with the first element.
  • The method is called again on the elements from second index to last index, where last index value would be excluded by design.
  • Otherwise, the function returns false.
  • Outside the function, the user is asked to enter a string.
  • This string is displayed on the console.
  • The method is called by passing this string as a parameter.
  • If its value computes to ‘True’, relevant message is displayed on the console.
  • Otherwise, a different message is displayed on the console.
Published on 12-Mar-2021 16:52:55