Why does my Python function enter the else block when I use recursion to generate a Fibonacci list with 'else' in the if statement?

huangapple go评论63阅读模式
英文:

Why does my Python function enter the else block when I use recursion to generate a Fibonacci list with 'else' in the if statement?

问题

递归。该函数返回一个大致长度的简单斐波那契列表。

我们有一个函数,可以在没有 else 块的情况下正常工作。
但令人困惑的是,它也可以在有 else 块的情况下正确工作。

def sp_fibo_generation(length):
    if length <= 0:
        return [1]
    if length == 1:
        return [1, 1]
    else:              
        sp = sp_fibo_generation(length - 1)
        n = (sp[-1] + sp[-2])
        sp.append(n)
        return sp

是的,这段代码在没有 else 的情况下也可以正常工作。但为什么它带有 else 也能工作呢?

我尝试理解深度递归的原理。

英文:

Recursion. The function returns a simple Fibonacci list in an approximate length.

We have a function that can work properly without the else block.
But confusingly, it also works correctly with an else block.

def sp_fibo_generation(length):
    if length &lt;= 0:
        return [1]
    if length == 1:
        return [1, 1]
    else:              
        sp = sp_fibo_generation(length - 1)
        n = (sp[-1] + sp[-2])
        sp.append(n)
        return sp

Yes, the code will work correctly without else. But why it does it work with else?

I tried to understand the principle of deep recursion.

答案1

得分: 3

因为return退出函数。所以如果你跳过了第二个if并且仍然在函数内部,那么else:无论如何都是隐含的,除非你明确指定。

这两种风格都相当常见,所以我不会推荐其中一种优于另一种;但你可能想要尽量保持一致:要么将第二个if改为elif,要么删除最后的else:并将该块的缩进去掉。

英文:

Because return exits the function. So if you fall off the second if and are still within the function, the else: is implicit anyway if you don't make it explicit.

Both styles are reasonably common, so I won't recommend one above the other; but you probably want to try to be consistent: Either change the second if to elif, or remove the final else: and remove the indentation from that block.

huangapple
  • 本文由 发表于 2023年6月1日 17:51:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定