Python Palindrome程序无法正常工作 [英] Python palindrome program not working

查看:98
本文介绍了Python Palindrome程序无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python写了一个简单的程序,检查句子是否是回文.但是我不知道为什么它不起作用.结果始终为False.有人知道怎么了吗?

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 knows what's wrong?

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)

推荐答案

您没有返回函数的结果.

You aren't returning the result of the function.

替换:

if word[0] == word[-1]:
    isPalindrome(word[1:-1])

使用

if word[0] == word[-1]:
    return isPalindrome(word[1:-1])

这篇关于Python Palindrome程序无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆