How to Find the Factorial of a Number Using Python

How to Find the Factorial of a Number Using Python

5 mins read9.5K Views Comment
clickHere
Updated on Jan 23, 2023 17:54 IST

In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module.

2022_06_MicrosoftTeams-image-16.jpg

While practicing Python programming as a beginner, or even during Python interviews, one of the most common programs you will be asked to write is going to be Python factorial. And in this article, we will discuss 5 different ways to find the factorial of a given number using Python. Let’s begin!

Table of Content

What is a Factorial?

The factorial of a given number is the product of all positive integers between 1 and the number itself. Mathematically, the factorial of a number is represented by “!”.

For example, the factorial of 6 would be given as –

2022_06_factorial-of-six.jpg

Note:

  • The factorial of negative numbers is not defined.
  • The factorial of 0 = 0! = 1.
How to Find Square Root of a Number Using Python
How to Find Square Root of a Number Using Python
The below article demonstrates different ways to find the Square Root of a Number using Python programming language.
How to Reverse a String in Python
How to Reverse a String in Python
In Python programming, strings are a sequence of characters or symbols. As a beginner practicing Python string operations, you will often come across problems that need you to work with...read more
Fibonacci Number
Fibonacci Number
In this article, we will discuss Fibonacci numbers, it’s application and how to generate them using Python, Java and C.

Methods to Find the Factorial of a Number in Python

Using for loop

In this method, we use a for loop to find the factorial of a non-negative input number n. Remember that the range() function does not include the stop value. Hence, the range of the for loop has to be iterated from 1 to (n+1).

Each number in the defined range is cumulatively multiplied and stored in a variable fact which is initialized to 1, as shown:

#Enter input= int(input("Enter input number : "))
 
fact = 1
if n < 0:
    print("Factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, n + 1):
        fact = fact * i
    print("The factorial of",n,"is",fact)

Output:

2022_06_image-229.jpg

What have we done here?

  • Firstly, we take an integer input from the user and store it in the variable n.
  • Declare and initialize the variable fact to 1.
  • Then, we will use if-elif-else statement to check if the input number is negative, 0, or positive.
  • For positive input integer, we will use the for loop and define the range() from 1 to n+1.
  • The loop then calculates the factorial of the input number.
  • Print the final factorial value stored in the variable fact.
Python Split() Function for Strings
Python Split() Function for Strings
The below article goes through explaining and implementing split function in python with suitable examples.
Python Join() Function
Python Join() Function
During Python programming, you might encounter instances where you would need to create strings from iterable objects. For example, building a sentence from a sequence of words. For this, the...read more
Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more

Must Check: What is Python

Using while loop

In this method, we use the while loop to find the factorial of a non-negative input number n.

Here too, each number is cumulatively multiplied and stored in a variable fact which is initialized to 1, as shown:

#Enter input= int(input("Enter input number : "))
 
fact = 1
if n < 0:
    print("Factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
  while(> 0):
        fact = fact * n
        n = n - 1
  print("The factorial is",fact)

Output:

2022_06_image-232.jpg

What have we done here?

  • Firstly, we take an integer input from the user and store it in the variable n.
  • Declare and initialize the variable fact to 1.
  • Then, we will use if-elif-else statement to check if the input number is negative, 0, or positive.
  • For positive input integer, we will use the while loop to multiply the value of n with the value stored in the fact variable.
  • The value of n is decremented by one each time the loop executes.
  • The loop runs until n becomes zero.
  • Print the final factorial value stored in the variable fact.

Must Check: Python Online Courses & Certifications

Using a ternary operator

In this method, instead of using a fact variable, we use a function and a conditional expression that calculates the factorial of a positive integer based on the given condition being true or false.

The syntax of a ternary operator is given as:

[on_true] if [expression] else [on_false]

This makes the code compact by testing the condition in a single line and replacing the multi-line if-else statements.

#Define a function
def factorial(n):
    return 1 if (n==1 or n==0) else n * factorial(n-1);
 
#Enter input= int(input("Enter input number : "))
 
print("The factorial of",n,"is",factorial(n))

Output:

2022_06_image-233.jpg

What have we done here?

  • We define a function factorial() that accepts an integer argument – n.
  • Inside the loop body, we use a ternary operator:
    • Return 1, if the input number is 0 or 1; because the factorial will be 1.
    • else, for any other positive integer input, multiply the value of n with factorial(n-1) and return the final factorial value.
  • Call the function and print the factorial of the given input number.

Using recursion

In this method, we calculate the factorial of a number using recursion, which is the process where a defined function can call itself.

#Define a function
def rec_factorial(num):
   if (num==1):
       return num
   else:
       return num * rec_factorial(num-1)
 
#Enter input= int(input("Enter input number : "))
 
if n < 0:
   print("Factorial does not exist for negative numbers")
elif n == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of",n,"is",rec_factorial(n))

Output:

2022_06_image-234.jpg

What have we done here?

  • We define a function rec_factorial() that accepts an integer argument – num.
  • Inside the loop body, we use an if-else statement:
    • if the input number is 1, the factorial will be 1 as well. So, return num.
    • else, for any other positive integer input, multiply the value of num with rec_factorial(num-1) and return the final factorial value.
  • Take the input integer from the user and store it in the variable n.
  • Use the if-elif-else statement to check if the input number is negative, 0, or positive.
  • For a positive input integer, we will call the function and print the factorial of the given input number.

Using math module – factorial()

One of the easiest methods to find the factorial of a number is to use an in-built factorial() function in the Python math library, that directly returns the factorial of any non-negative number when applied to it:

#Import the math library 
import math 
 
#Enter input= int(input("Enter input number : "))
 
if n < 0:
   print("Factorial does not exist for negative numbers")
elif n == 0:
   print("The factorial of 0 is 1")
else:
  print("The factorial of",n,"is", math.factorial(n))

Output:

2022_06_image-235.jpg

What have we done here?

  • We first import the math module of Python.
  • Then, we take an integer input from the user and store it in the variable n.
  • Next, we will use if-elif-else statement to check if the input number is negative, 0, or positive.
  • For positive input integer, we will call the math.factorial() method to directly calculate and print the factorial of the number.
All About Operators in Python
All About Operators in Python
Python has many operators that you can use in your program. This article will teach you more about them.
String Formatting in Python
String Formatting in Python
In this article we discussed different techniques of string formatting in python like modulo operator, built-in format and f-string.
Series vs. DataFrame in Pandas – Shiksha Online
Series vs. DataFrame in Pandas – Shiksha Online
In this tutorial, we are going to learn the two most common data structures in Pandas – Series and DataFrame. 

Conclusion

The factorial of a number frequently finds its applications in data analysis alongside high-level mathematical problems. Hope this article was helpful for you to understand how to find the factorial of a number using different methods in Python.

Top Trending Articles:

Data Analyst Interview Questions | Data Science Interview Questions | Machine Learning Applications | Big Data vs Machine Learning | Data Scientist vs Data Analyst | How to Become a Data Analyst | Data Science vs. Big Data vs. Data Analytics | What is Data Science | What is a Data Scientist | What is Data Analyst

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments