Check Palindrome String Recursively

Check if string is palindrome recursively.

AdvancedPhase 3 - Level 4: String-based RecursionExample 2 of 10
check-palindrome-string-recursively.py
1def is_palindrome(s):
2 # Base case
3 if len(s) <= 1:
4 return True
5
6 # Check first and last
7 if s[0].lower() != s[-1].lower():
8 return False
9
10 # Recurse on middle
11 return is_palindrome(s[1:-1])
12
13# Test
14text = input("Enter a string: ")
15if is_palindrome(text):
16 print("Palindrome")
17else:
18 print("Not a palindrome")

Output

Enter a string: racecar
Palindrome

Enter a string: hello
Not a palindrome

What's going on

Compare first and last, recurse on middle.

Key Concepts:

Base case: empty or single character
Check first == last
Recurse on s[1:-1] (middle part)