Python返回值不正确,没有获得'True'返回值

问题描述 投票:1回答:3

我期待返回True,但是返回None。

我在代码中放了一些print语句来帮助调试。它显示'print(“Got True”)'语句运行,因此我知道代码在'return True'之前的代码的右分支中结束但由于某种原因我得到'None'。然而,当我输入一个不是回文的单词时,'return False'完美无缺。

谢谢您的帮助。

def first(word):
    return word[0]

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

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

def is_palindrome(word):
    print(word)
    if len(word) <= 1:
        print("Got True")
        return True
    else:
        print(len(word))
        if first(word) == last(word):
            is_palindrome(middle(word))
        else:
            print("Got False")
            return False

print(is_palindrome('allen'))
print("\n")
print(is_palindrome('redivider'))

输出:

allen
5
Got False
False


redivider
9
edivide
7
divid
5
ivi
3
v
Got True
None
python return-value palindrome
3个回答
1
投票

你需要在函数的每个分支中返回,例如:

def is_palindrome(word):
    print(word)
    if len(word) <= 1:
        print("Got True")
        return True
    else:
        print(len(word))
        if first(word) == last(word):
            return is_palindrome(middle(word))  # **Added return**
        else:
            print("Got False")
            return False

但是你可以简化结构,因为如果你return然后你不需要else:子句因为它无法到达,所以这可以写成:

def is_palindrome(word):
    print(word)
    if len(word) <= 1:
        print("Got True")
        return True

    print(len(word))
    if first(word) == last(word):
        return is_palindrome(middle(word))

    print("Got False")
    return False

1
投票

即使在递归函数中,您也必须使用return语句来返回值:

   if first(word) == last(word):
        return is_palindrome(middle(word))

0
投票

您应该在每个可能的条件分支中返回结果。您可以直接使用return语句或在某个变量中捕获is_palindrome函数的结果,如果它令人困惑则返回它。

© www.soinside.com 2019 - 2024. All rights reserved.