Python Calculate 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 as n!. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The following is a Python function that calculates 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)}")
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 explanation:
def factorial(n):Defines a function namedfactorialthat accepts a parametern。if n == 0 or n == 1:Checknwhether it is 0 or 1; if so, return 1, because both 0! and 1! equal 1.else:Ifnis not 0 or 1, then recursively callfactorial(n - 1)and multiply bynuntilnit decreases 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 120Other Extensions
Python3 Examples