I\'ve written a simple program in python which checks if the sentence is palindrome. But I can\'t figure out why isn\'t it working. The results is always False. Does anyone know
You need to replace "input" with "raw_input". Also, you are calling isPalindrome recursively and there is a mistake here as well. It should be:
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
else:
return False
Check the corrected code below:
def isPalindrome(word):
# Removes all spaces, and lowercase the word.
word = word.strip().lower()
word = word.replace(" ", "")
# If the length of the word is less than 1, means its a palindrome
if (len(word) <= 1):
return True
# Compares the first and the last character of the word.
# If it is the same, calls the function again with the same word, without its first and last characters.
# If its not the same, its not palindrome
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
else:
return False
sentence = raw_input("Enter a sentence: \n")
if (isPalindrome(sentence)):
print("The sentence %s is palindrome." % sentence)
else:
print("The sentence %s is NOT palindrome" % sentence)