英文:
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 <= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论