Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python computing the factorial of a given number

Python computing the factorial of a given number

Document Object Reference Manual Python3 Examples

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

print

(

f

"The factorial of {number} is {factorial(number)}"

)

Code analysis:

  1. def factorial(n): defines a class named factorial function, which takes a parameter n。
  2. if n == 0 or n == 1: Checks n is 0 or 1; if so, it returns 1, because 0! and 1! both equal 1.
  3. else: If both the n is not 0 or 1, it recursively calls factorial(n - 1) and multiplies by n, until n is reduced to 1.
  4. number = 5 Set a variable number to 5, to test the function.
  5. print(f"The factorial of {number} is {factorial(number)}") Print the factorial result of 5.

Output result:

The factorial of 5 is 120

Document Object Reference Manual Python3 Examples