Python Program to Check whether a String is Palindrome or not using Recursion

This is a Python Program to check whether a string is a palindrome or not using recursion.

Problem Description

The program takes a string and checks whether a string is a palindrome or not using recursion.

Problem Solution

1. Take a string from the user.
2. Pass the string as an argument to a recursive function.
3. In the function, if the length of the string is less than 1, return True.
4. If the last letter is equal to the first letter, recursively call the function with the argument as the sliced list with the first character and last character removed else return False.
5. Use an if statement if check if the returned value is True of False and print the final result.
6. Exit.

Program/Source Code

Here is source code of the Python Program to check whether a string is a palindrome or not using recursion. The program output is also shown below.

def is_palindrome(s):
    if len(s) < 1:
        return True
    else:
        if s[0] == s[-1]:
            return is_palindrome(s[1:-1])
        else:
            return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
    print("String is a palindrome!")
else:
    print("String isn't a palindrome!")
Program Explanation

1. User must enter a string.
2. The string is passed as an argument to a recursive function.
3. In the function, if the length of the string is less than 1, True is returned.
4. If the last letter is equal to the first letter, the function is called recursively with the argument as the sliced list with the first character and last character removed, else return False.
5. The if statement is used to check if the returned value is True or False and the final result is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter string:mom
String is a palindrome!
 
Case 2:
Enter string:hello
String isn't a palindrome!

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.