You can use a recursive function in Python to easily check if a word is a palindrome.
def checkPalindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return checkPalindrome(word[1:-1])
print(checkPalindrome("hello"))
print(checkPalindrome("anna"))
#Output:
False
True
When working in Python, recursion and recursive functions are very useful and powerful if used correctly.
One such case where recursion can be used is if we want to check if a word is a palindrome or not.
A palindrome is a word which is the same spelled forward and backward.
For recursion, we need to define a base case and a recursive step.
The base case for our recursive palindrome function is if our word has less than two letters. By definition, a word which is 0 or 1 letters is a palindrome.
The recursive step for our recursive palindrome function is to check if the first letter and last letter are equal. If they are equal, then we should remove the first and last character and check the resulting string.
In the case the first and last characters are not equal, then we should return False since the given word is not a palindrome.
Below is a function which will check if a word is a palindrome using recursion in Python.
def checkPalindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return checkPalindrome(word[1:-1])
print(checkPalindrome("hello"))
print(checkPalindrome("anna"))
#Output:
False
True
Hopefully this article has been useful for you to learn how to make a recursive function to check if a word is a palindrome in Python.