• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python math.factorial() function – Calculate Factorial of Number

Python math.factorial() function – Calculate Factorial of Number

February 4, 2022 Leave a Comment

In Python, the easiest way to find the factorial of an nonnegative integer number is with the Python factorial() function from the math module.

import math 

factorial_of_5 = math.factorial(5)

The Python math module has many powerful functions which make performing certain calculations in Python very easy.

One such calculation which is very easy to perform in Python is finding the factorial of a number.

We can find the factorial of a number easily with the Python math module factorial() function.

To do so, we need to pass a nonnegative integer number to math.factorial()

Below are a few examples of how to use the factorial() function to find the factorial of different numbers with in Python.

import math

print(math.factorial(3))
print(math.factorial(5))
print(math.factorial(8))
print(math.factorial(12))

#Output: 
6
120
40320
479001600

We can also define our own functions to calculate factorials using recursion or factorials with for loops in Python.

Using Recursion to Calculate Factorial of Number in Python

In Python, we can use recursion to calculate the factorial of a number. To calculate the factorial of a number in Python using recursion, we need to define the base case, and then define the recursive step.

The base case for the factorial function is when n is 0 or 1. In that case, we want to return 1. If n is greater than 1, then we will call the function again with n – 1 as the input.

Below is a recursive function for calculating the factorial of a number. I’ve also included some input validation to make sure that the input is a nonnegative integer.

def factorial_with_recursion(n):
    if isinstance(n,int) and n >= 0: 
        if n == 0 or n == 1: 
            return 1
        else:
            return n * factorial_with_recursion(n-1)
    else: 
        return "Not valid input"

print(factorial_with_recursion(3))
print(factorial_with_recursion(5))
print(factorial_with_recursion(8))
print(factorial_with_recursion(12))

#Output:
6
120
40320
479001600

As you can see, we receive the same results as we did from using the Python math factorial() function.

Using Iteration to Calculate Factorial of Number in Python

We can also use iteration to find the factorial of a number in Python. We can use a for loop in our Python code to define a function which will calculate factorials for us.

To do so, we just need loop from 1 to n, and get the cumulative product of the index.

Below is a iterative function for calculating the factorial of a number. I’ve also included some input validation to make sure that the input is a nonnegative integer.

def factorial_with_iteration(n):
    if isinstance(n,int) and n >= 0: 
        if n == 0: 
            return 1
        else:
            factorial = 1
            for x in range(1, n + 1): 
                factorial = factorial * x
            return factorial
    else: 
        return "Not valid input"

print(factorial_with_iteration(3))
print(factorial_with_iteration(5))
print(factorial_with_iteration(8))
print(factorial_with_iteration(12))

#Output:
6
120
40320
479001600

As you can see, we receive the same results as we did from using the Python math factorial() function.

Hopefully this article has been useful for you to learn how to use Python to calculate factorials.

Other Articles You'll Also Like:

  • 1.  pandas to_pickle – Write DataFrame to Pickle File
  • 2.  Creating a Random Color Turtle in Python
  • 3.  Remove All Instances of Value from List in Python
  • 4.  Multiply Each Element in List by Scalar Value with Python
  • 5.  Python Check if Object Has Attribute
  • 6.  How to Remove All Punctuation from String in Python
  • 7.  Using Python to Split String by Tab
  • 8.  Python Get Yesterday’s Date
  • 9.  Find Magnitude of Complex Number in Python
  • 10.  Using Python to Remove Quotes from String

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy

x