Python递归

中的功能Python可以自称。这就是递归。在许多情况下,它可能非常有用。

解释递归的常用方法是使用阶乘计算。

数字的阶乘是数字nn-1,乘以n-2…依此类推,直到达到数字1

3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120

Using recursion we can write a function that calculates the factorial of any number:

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

print(factorial(3)) # 6 print(factorial(4)) # 24 print(factorial(5)) # 120

If inside the factorial() function you call factorial(n) instead of factorial(n-1), you are going to cause an infinite recursion. Python by default will halt recursions at 1000 calls, and when this limit is reached, you will get a RecursionError error.

Recursion is helpful in many places, and it helps us simplify our code when there’s no other optimal way to do it, so it’s good to know this technique.


More python tutorials: