Home >Backend Development >Python Tutorial >How to find factorial recursively in Python

How to find factorial recursively in Python

angryTom
angryTomOriginal
2020-02-13 11:23:3021694browse

How to find factorial recursively in Python

How to find factorial recursively in python

Factorial: For example, 5! refers to the "factorial of 5", that is, 5! = 1* 2*3*4*5.

"Recursion" is a function that calls itself.

Recommended learning: Python video tutorial

def f(x):
    if x == 0:
        return 0
    elif x == 1:
        return 1
    else:
        return (x * f(x-1))
print(f(5))

Code explanation: If x=5, then return the value of 5*f(4). If you want to know this value, you must first calculate what f(4) is equal to. According to the function f(x), f(4) = 4*f(3), so f(5) = 5*4*f(3). By analogy, f(5) = 5*4*3*2*f(1). Function f(x) says that when x==1, the return value is 1. So: f(5) = 5*4*3*2*1 = 120. Therefore, the output result is as follows:

120

It sounds very troublesome and hard to understand. What if we don’t use recursive functions? Using the most basic code, it can be written as:

f = 1
for i in range(1,6):
    f = f * i
print(f)

The result is still 120.

The above is the detailed content of How to find factorial recursively in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn