Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive Function for Palindrome Check - Python Program

Example 1 :

def is_palindrome(s): """Check palindrome recursively.""" s = s.lower().replace(" ", "") if len(s) <= 1: return True return s[0] == s[-1] and is_palindrome(s[1:-1]) print(is_palindrome("Madam"))

Output

 
OUTPUT  :
True

Example 2 : Advanced Program

def is_palindrome_recursive(s): # Base case 1: If the string is empty or has only one character, it's a palindrome. if len(s) <= 1: return True # Base case 2: If the first and last characters don't match, it's not a palindrome. elif s[0] != s[-1]: return False # Recursive step: Check the substring excluding the first and last characters. else: return is_palindrome_recursive(s[1:-1]) # Example to input a string and check : a=str(input("Enter a String : ")) if(is_palindrome_recursive(a)==True): print("String is a Palindrome!") else: print("String is not a Palindrome!")

Output

 
OUTPUT 1 :
Enter a String : malayalam
String is a Palindrome!
 
OUTPUT 2 :
Enter a String : Madam
String is not a Palindrome!