Python computing the factorial of a given number
Factorial is a mathematical concept: the factorial of a positive integer n is the product of all positive integers less than or equal to n, denoted n!. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. Below is a function written in Python to compute the factorial.
Example
def
factorial
(
n
)
:
if
n
==
0
or
n
==
1
:
return
1
else
:
return
n * factorial
(
n -
1
)
Test the function
number
=
5
(
f
"The factorial of {number} is {factorial(number)}"
)
Code analysis:
def factorial(n):defines a class namedfactorialfunction, which takes a parametern。if n == 0 or n == 1:Checksnis 0 or 1; if so, it returns 1, because 0! and 1! both equal 1.else:If both thenis not 0 or 1, it recursively callsfactorial(n - 1)and multiplies byn, untilnis reduced to 1.number = 5Set a variablenumberto 5, to test the function.print(f"The factorial of {number} is {factorial(number)}")Print the factorial result of 5.
Output result:
The factorial of 5 is 120
Python3 Examples