Python递归阶乘函数

编程入门 行业动态 更新时间:2024-10-27 00:33:47
本文介绍了Python递归阶乘函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

找到了此解决方案来在python中创建 factorial() 函数,但是我在理解"为什么"有效时遇到了麻烦.

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

函数是:

def factorial(x): if x <= 1: return 1 else: return x * factorial(x-1)

我无法理解实际乘法发生在哪里?

在我看来,该函数将不断调用自身,直到达到1,然后返回1.有人可以启发我吗?我确定我缺少简单的东西.

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.

推荐答案

编程的一般技巧是插入print语句,以帮助您了解代码运行时发生的情况.当您破坏了要修复的代码时,这特别有用,同时也有助于理解新代码.在这种情况下,请尝试运行以下命令:

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)

更多推荐

Python递归阶乘函数

本文发布于:2023-11-29 19:39:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   阶乘   函数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!