Exercise
Recursive Palindrome Function
Objective
Develop a Python program with a recursive function to determine if a string is symmetric (a palindrome). For example, "RADAR" is a palindrome.
Example Python Exercise
Show Python Code
# Recursive function to check if a string is a palindrome
def is_palindrome(s):
# Base case: if the string has 0 or 1 character, it is a palindrome
if len(s) <= 1:
return True
# Compare the first and last character
if s[0] != s[-1]:
return False # If characters don't match, it's not a palindrome
# Recursive case: check the substring without the first and last characters
return is_palindrome(s[1:-1])
# Example strings to test
test_strings = ["RADAR", "hello", "madam", "world"]
# Check if each string is a palindrome
for test_string in test_strings:
result = is_palindrome(test_string)
print(f"Is '{test_string}' a palindrome? {result}")
Output
python recursive_palindrome.py
Is 'RADAR' a palindrome? True
Is 'hello' a palindrome? False
Is 'madam' a palindrome? True
Is 'world' a palindrome? False
Share this Python Exercise