-2

Good evening folks,

I'm working on an assignment for a course in Python. Our job is to write a function that returns True if the string it takes is a palindrome, otherwise it returns False. The following code reports False to the console for nonpalindromes, but does not report anything to the console when it is a palindrome. I hypothesize it's getting lost in either the recursive call or the second elif statement, but I really don't know where it's going wrong. Any help greatly appreciated :) Here's the code:

def middle(word):
    return word[1:-1]

def last(word):
    return word[-1]

def first(word):
    return word[0]

def isPalindrome(word):
    if(len(word)<1):                        
        print("You entered a blank word!")
    elif(len(word)==1):  
        return True 
    elif(first(word)==last(word)): 
        if(middle(word)==''):
            return True
        isPalindrome(middle(word))
    else:
        return False

2 Answers2

0

There are much easier ways to check for palindrome using Python. That aside, for your current approach you'll need to return the output of the recursive call, else your function will return None in that elif branch:

return isPalindrome(middle(word))

You can, for example, simply reverse the string and check if the reversed and original string are equal:

word == word[::-1]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0
def isPalindrome(word):
    return word == word[::-1]

word[::-1] reverses word. This checks whether word backwards is the same as word.

Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Filipe Teixeira
  • 479
  • 1
  • 7
  • 26