This Python program checks whether a string is a palindrome using recursion. word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, “radar,” “level,” and “deified” are palindromes.
You are required to write a Python program that uses recursion to determine whether a given string is a palindrome or not. A palindrome is a string that reads the same forwards as it does backwards. Your program should take a string as input and output whether the string is a palindrome or not.
Python Program to Check whether a String is Palindrome or not using Recursion
def is_palindrome(s): # Base case: if the string is empty or has only one character, it's a palindrome if len(s) <= 1: return True # Compare the first and last characters, and check the rest of the string recursively if s == s[-1]: return is_palindrome(s[1:-1]) else: return False # Get input from the user input_string = input("Enter a string: ") if is_palindrome(input_string): print("The string is a palindrome.") else: print("The string is not a palindrome.")
How it Works
is_palindromefunction takes a string
sas input and returns
Trueif the string is a palindrome and
- The base case of the recursion is when the length of the string
sis less than or equal to 1. In this case, a string with one character or an empty string is considered a palindrome, so the function returns
- If the string has more than one character, the function checks if the first and last characters are equal. If they are, it proceeds to the next step. If not, it immediately returns
Falseas the string is not a palindrome.
- If the first and last characters are equal, the function makes a recursive call to itself with the substring of the input string excluding the first and last characters (
s[1:-1]). This effectively removes the first and last characters from the string.
- The recursive call continues to apply the same logic on the shortened string, checking the characters at the new first and last positions.
- This process continues until the base case is reached or until a mismatched pair of characters is found. If a mismatch is found at any point during the recursion,
Falseis returned immediately.
- If the recursion completes without finding any mismatches, and the base case is reached for each substring, then the function returns
True, indicating that the original string is a palindrome.
- The main part of the program takes user input for a string and calls the
is_palindromefunction to determine whether the input string is a palindrome or not. It then prints the appropriate message based on the returned result.