Bytes
PythonData Science

Factorial Program in Python(Factorial of a Number in Python)

Last Updated: 19th October, 2024
icon

Arunav Goswami

Data Science Consultant at almaBetter

Learn to write a factorial program in Python using for loops, while loops, recursion, and functions with code examples, detailed explanations and use cases

The factorial of a number is an essential concept in mathematics and programming. It is denoted as n!, which represents the product of all positive integers from 1 to n. For example, the factorial of 5 (written as 5!) is calculated as:

5!=5×4×3×2×1=120

In Python, calculating the factorial of a number can be done in several ways: using loops, recursion, or built-in functions. In this article, we will explore various ways to write a program to find the factorial of a number in Python, covering loops and recursion.

What is the Factorial of a Number?

Factorial is the product of all positive integers up to a given number. Mathematically, it is expressed as:

n!=n×(n−1)×(n−2)×⋯×1

Special Case:

  • The factorial of 0 is defined as 1 (0! = 1).

Factorial Program in Python Using For Loop

A for loop is one of the simplest ways to calculate the factorial of a number in Python. Here's how you can implement it:

def factorial_for_loop(n):
    factorial = 1
    forin range(1, n + 1):
        factorial *= i
    return factorial

# Example
number = 5
print(f"Factorial of {number} using for loop is:", factorial_for_loop(number))

Explanation:

  • The factorial_for_loop function takes an integer n as input.
  • A loop runs from 1 to n, multiplying each number and storing the result in the factorial variable.
  • The final result is returned after the loop completes.

Output:

Factorial of 5 using for loop is: 120

Factorial Program in Python Using While Loop

The while loop can also be used to calculate the factorial of a number. Here's a Python program to achieve that:

def factorial_while_loop(n):
    factorial = 1
    while n > 0:
        factorial *= n
        n -= 1
    return factorial

# Example
number = 5
print(f"Factorial of {number} using while loop is:", factorial_while_loop(number))

Explanation:

  • The factorial_while_loop function uses a while loop that continues to multiply the current value of n and decrements n in each iteration until it reaches 0.

Output:

Factorial of 5 using while loop is: 120

Factorial Program in Python Using Recursion

Recursion is a powerful concept where a function calls itself to solve smaller instances of the same problem. Here's how you can calculate the factorial using recursion:

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

# Example
number = 5
print(f"Factorial of {number} using recursion is:", factorial_recursion(number))

Explanation:

  • The factorial_recursion function checks for the base case (n == 0 or n == 1), where it returns 1.
  • Otherwise, it multiplies n by the factorial of n-1, recursively calculating the factorial.

Output:

Factorial of 5 using recursion is: 120

Recursive Process Breakdown:

For n = 5, the recursive function operates as follows:

factorial_recursion(5) = 5 * factorial_recursion(4)
factorial_recursion(4) = 4 * factorial_recursion(3)
factorial_recursion(3) = 3 * factorial_recursion(2)
factorial_recursion(2) = 2 * factorial_recursion(1)
factorial_recursion(1) = 1 (base case)

Factorial Program in Python Using Function

It’s common to encapsulate the factorial logic into a reusable Python function, which can be invoked multiple times with different values. Here’s an example:

def factorial(n):
    if n == 0:
        return 1
    else:
        result = 1
        forin range(1, n + 1):
            result *= i
        return result

# Example
number = 6
print(f"Factorial of {number} is:", factorial(number))

Explanation:

  • The factorial function is a general implementation that uses a for loop inside a function, returning the factorial result.

Output:

Factorial of 6 is: 720

Using Python's Built-in Function

If you prefer not to implement your own function, Python's math library provides a built-in function to calculate factorials.

import math

number = 5
print(f"Factorial of {number} using math.factorial is:", math.factorial(number))

Output:

Factorial of 5 using math.factorial is: 120

The math.factorial function handles the calculation internally and is highly optimized.

Use Cases of Factorial in Python

Factorials are important in mathematics and computer science because they help solve problems involving counting, arrangements, and probabilities. Here are a few key use cases:

1. Combinatorics:

Factorials are used to calculate permutations (arrangements) and combinations (selections) of objects. For example, the number of ways to arrange n objects is given by n!.

2. Probability:

Factorials are essential in probability calculations, especially in problems involving random selections or outcomes. They help compute the number of possible outcomes in events like lotteries or games.

3. Algorithms:

In computer science, factorials are used in recursive algorithms and problems like the traveling salesman problem, where all possible solutions must be evaluated.

4. Mathematical Series:

Factorials appear in expansions like the Taylor series, used to approximate functions in calculus.

5. Biology and Genetics:

Factorials help compute the possible sequences in DNA or protein structures, vital in genetics and bioinformatics.

6. Optimization Problems:

Factorials are used in scheduling, logistics, and pathfinding problems, where all possible routes or arrangements need to be considered.

Enhance your skills with our Python tutorial, explore the Python cheat sheet, and try our latest tool the online Python compiler!

Conclusion

In this article, we explored multiple ways to calculate the factorial of a number in Python and python programs to find factorial of a number, including the use of for loopswhile loopsrecursion, and Python's built-in function. Each method has its use case:

  • For loops: Easy to understand and efficient for small to medium-sized inputs.
  • While loops: Offers flexibility if you need more control over the loop termination condition.
  • Recursion: Elegant but may face limitations due to Python's recursion depth limits for large inputs.
  • Built-in functions: Fast and optimized, recommended for large-scale applications.

Take the next step in your career with our data science course or advance further with a masters in data science!

Related Articles

Top Tutorials

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter