Python Program to Find the Factorial of a Number

Created with Sketch.

Calculating Factorial in Python: A Step-by-Step Guide with Examples

Factorials are fundamental in mathematics and often needed in various programming tasks. In this blog post, we’ll explore how to write a Python program to find the factorial of a number. Additionally, we’ll provide a step-by-step explanation and include example code with outputs.

Understanding Factorials

The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n. Mathematically, it is expressed as:

n!=n×(n−1)×(n−2)×…×3×2×1

For example:

  • 5!=5×4×3×2×1=120
  • 0!=1 (by convention)

Python Program to Find the Factorial of a Number

Let’s create a Python program that calculates the factorial of a given number. We’ll use both iterative and recursive approaches for a comprehensive understanding.

Iterative Approach

def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# Example Usage
number = 5
result_iterative = factorial_iterative(number)
print(f"The factorial of {number} (iterative) is: {result_iterative}")

Output:

 
The factorial of 5 (iterative) is: 120

Recursive Approach

 
def factorial_recursive(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial_recursive(n - 1)

# Example Usage
number = 5
result_recursive = factorial_recursive(number)
print(f"The factorial of {number} (recursive) is: {result_recursive}")

Output:

 
The factorial of 5 (recursive) is: 120

Step-by-Step Explanation

Iterative Approach

  1. We initialize a variable result to 1 as the initial value for the factorial.
  2. Using a for loop, we iterate from 1 to n (inclusive).
  3. In each iteration, we multiply the current value of result by the loop variable.
  4. The final value of result is the factorial of n.

Recursive Approach

  1. The base case checks if n is 0 or 1. If true, it returns 1.
  2. If n is greater than 1, the function calls itself with the argument n-1 and multiplies the result by n.
  3. The recursion continues until reaching the base case.

Conclusion

Calculating factorials is a common mathematical operation, and understanding how to implement it in Python is valuable. Whether you choose an iterative or recursive approach, the concept remains the same. Use this knowledge to solve problems involving permutations, combinations, and more.

Leave a Reply

Your email address will not be published. Required fields are marked *