How to use recursive methods in Python to calculate the factorial of n?

In Python, recursion can be used to calculate the factorial of n. Here is an example code:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

n = 5
result = factorial(n)
print(f"{n}的阶乘是: {result}")

The code above defines a recursive function called factorial that calculates the factorial of n. In the function, if n equals 0, it returns 1; otherwise, it recursively calls the factorial function to calculate the factorial of n-1 and returns n multiplied by that value. Finally, the factorial function is called by passing a specific n value and printing the result.

bannerAds