python递归调用阶乘求和,Python递归阶乘函数

Found this solution to make a factorial() function in python, but I am having trouble with understanding 'why' it works.

The function is :

def factorial(x):

if x <= 1:

return 1

else:

return x * factorial(x-1)

I'm having trouble understanding where the actual multiplication happens?

It would seem to me, that the function would keep calling itself until it gets to 1, and returns 1. Can someone enlighten me? I'm sure I'm missing something easy.

解决方案

A general tip for programming is to insert print statements to help you see what's happening as the code runs. This is especially useful when you have broken code that you are trying to fix but is also good for understanding new code. In this case try running the following:

def factorial(x):

print "x", x

if x <= 1:

print "base case, returning 1"

return 1

else:

sub_fact = factorial(x-1)

print "factorial(x-1)", sub_fact

result = x * sub_fact

print "return", result

return result

factorial(4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值