I am trying to write my first recursive function in Python. It is supposed to take a word as input and then check whether that word is a palindrome or not.
Here is my code:
def checkPalindrome(str):
if len(str) == 1:
return True
elif str[0] == str[len(str)-1]:
newstr = str.replace(str[0], "")
newstr = str.replace(str[len(str)-1], "")
checkPalindrome(newstr)
def main():
word = raw_input("Give a name: ")
if checkPalindrome(word):
print '%s is a palindrome' % word
else:
print '%s is NOT a palindrome' % word
if __name__ == '__main__':
main()
The problem I am having is that the function checkPalindrome() only works for 1 letter palindromes. It only returns True with something like "k". It also correctly returns false for non palindromes.
But here is the problem: if I give my program a palindrome like wowow, it should return True by calling itself until the string is only 1 character long, in which case it should return true by checking the string is of length 1. But when my program gets to return True after the recursion and after the string has only one character left it returns False!
I even checked that the line of code "return True" is actually ran (through the debugger), and it is being run. But I end up with the else-statement in my main function even if I enter a palindrome.
Can someone with experience in recursion tell me why my function seems to return False even though the line "return True" is being called when I enter a palindrome?