Python中的递归(阶乘函数) [英] Recursion in Python (factorial function)
本文介绍了Python中的递归(阶乘函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望这不是一个愚蠢的问题,但是为什么此Python代码中的'return 1'语句返回数字的阶乘?"return True"也会发生这种情况,据我所知,它等同于"return 1"
I hope this is not too much of a stupid question, but why does the 'return 1' statement in this Python code return the factorial of a number? This also happens for 'return True', which I understand is equivalent to 'return 1'
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
推荐答案
n == 0
是递归函数的基本情况.阶乘0是1:引用
n == 0
is the base case of the recursive function. Factorial of 0 is 1: reference
一旦基本案例返回1,则语句 return n * factorial(n-1)
将具有以下形式: return n * 1
,依此类推.
Once the base case returns 1, the statement return n * factorial(n-1)
will have the form: return n * 1
and so on.
这篇关于Python中的递归(阶乘函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文