In Python, there isn’t a built-in `factorial()` function directly available in the base language, but you can find it in the `math` module. Here’s how you can use it:
Using the `math.factorial()` Function
The `math.factorial()` function computes the factorial of a given non-negative integer.
Syntax
import math result = math.factorial(x) - x: A non-negative integer whose factorial is to be computed.
Example
import math # Calculate the factorial of 5 result = math.factorial(5) print("Factorial of 5 is:", result)
Output
Factorial of 5 is: 120
Explanation
– The factorial of a number `n` is the product of all positive integers less than or equal to `n`. It is denoted by `n!`.
– In the example, `5! = 5 × 4 × 3 × 2 × 1 = 120`.
– The `math.factorial()` function efficiently calculates this for you.
Custom Implementation of Factorial
If you want to write your own factorial function without using the `math` module, you can do it using recursion or iteration.
Example (Using Iteration)
def factorial(n): if n < 0: return "Factorial is not defined for negative numbers" result = 1 for i in range(1, n + 1): result *= i return result # Calculate the factorial of 5 result = factorial(5) print("Factorial of 5 is:", result)
Example (Using Recursion)
def factorial(n): if n < 0: return "Factorial is not defined for negative numbers" if n == 0 or n == 1: return 1 return n * factorial(n - 1) # Calculate the factorial of 5 result = factorial(5) print("Factorial of 5 is:", result)
Both of these examples will also produce the output:
Factorial of 5 is: 120
These implementations demonstrate different approaches to calculating the factorial of a number in Python.