我用 python 编写了一个简单的程序,它检查句子是否是回文。但我不明白为什么它不起作用。结果始终为 False。有谁知道出了什么问题吗?
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
else:
if word[0] == word[-1]:
isPalindrome(word[1:-1])
else:
return False
sentence = input("Enter a sentence: \n")
if (isPalindrome(sentence)):
print("The sentence %s is palindrome." % sentence)
else:
print("The sentence %s is NOT palindrome" % sentence)
您没有返回函数的结果。
代替 :
if word[0] == word[-1]:
isPalindrome(word[1:-1])
with
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)