【问题标题】:Why does this happen when using recursion in python?为什么在 python 中使用递归时会发生这种情况?
【发布时间】:2021-10-18 15:50:53
【问题描述】:

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

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

【问题讨论】:

标签: python recursion


【解决方案1】:

这是因为在 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 不能与递归函数一起使用,可以使用带有 return 语句或不带任何语句的函数。

    【讨论】:

    • 如果您认为这是您的答案,请随时接受我的回答 :))
    【解决方案3】:

    @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 的数字,你就会遇到麻烦,因为它会无限递归。所以在这种情况下我们可以抛出异常。

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 2013-08-02
      • 2018-12-19
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多