且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python递归阶乘函数

更新时间:2023-02-19 23:15:17

编程的一般技巧是插入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)