在使用Python递归时为什么会出现这种情况?

3

最近我在学习递归,我写了一个简单的递归函数来验证我的理解:

def hello(n):
    if n == 1:
        return 'hello'
    else:
        print('hello')
        hello(n-1)

def returnhello():
    return 'hello'

print(returnhello())
print()
print(hello(5))

这个的输出结果如下所示:
hello

hello
hello
hello
hello
None

为什么递归中的最后一个调用打印出 None 而不是 hello?我本来期望它能够打印出 5 个 hello。

重复问题:https://dev59.com/GmIk5IYBdhLWcg3wguX- https://dev59.com/DW_Xa4cB1Zd3GeqPyTXk https://dev59.com/UXE85IYBdhLWcg3wzm9p https://stackoverflow.com/questions/44061245/python-recursion-returning-none-value https://stackoverflow.com/questions/31739963/recursive-function-returning-none https://dev59.com/xW_Xa4cB1Zd3GeqP1n52 https://stackoverflow.com/questions/36692143/why-python-recursion-return-none-value - Stef
@Stef 请只投票关闭问题。如果您不知道哪个是规范问题,请在Python聊天室中询问或讨论,或尝试使用https://sopython.com/canon。 - Karl Knechtel
3个回答

5
这是因为在你的hello(n)函数中,else部分在调用hello(n-1)之前没有return语句,所以第一次调用(退出最后一个)会返回None
如果在hello(n-1)之前加上return语句,你应该就能得到想要的结果。

2
您期望的输出所需使用的正确递归函数为:
def hello(n):
    if n == 1:
        return 'hello'
    else:
        print('hello')
        return hello(n-1)

def returnhello():
    return 'hello'

print(returnhello())
print()
print(hello(5))

此外,它也可以写成:

def hello(n):
    if n==1:
        print("hello")
    else:
        print("hello")
        hello(n-1)
        
def returnhello():
    return 'hello'

print(returnhello())
print()
hello(5)

输出结果将是:
hello

hello
hello
hello
hello
hello

注意:

在递归函数中,不应该使用print语句,可以使用带有返回语句或者没有任何语句的函数。


如果您认为我的答案是正确的,请随意接受它:)) - Raha Moosavi

1
@saedx已经发现并纠正了你的问题。Python默认返回None,这就是函数返回后打印出来的内容。
你可以使你的hello函数在显示字符串时更加一致。目前,前n-1个字符串在函数体内打印,但调用者必须打印最后一个字符串。
此处函数打印所有n个字符串。
def hello(n):
    print('hello')
    if n > 1:
        hello(n-1)

hello(5)

在这种情况下,您只需调用函数。不要打印它返回的内容。
另一种方法是让调用者打印所有n个字符串。
def hello(n):
    yield 'hello'
    if n > 1:
        yield from hello(n-1)

然后被称为如下:
print('\n'.join(hello(5)))

同时请注意这两个示例都删除了要打印的字符串的重复。值得注意的是,如果您传入一个小于1的数字,就会陷入麻烦,因为它将无限递归。因此,在这种情况下,我们可以抛出异常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接