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
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Aug 16, 2024 15:25 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.

finding factorial of a number

 

While practising 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

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
3 months
– / –
2 weeks
– / –
16 weeks
β‚Ή1.7 K
3 months
– / –
– / –
β‚Ή4.24 K
2 weeks
β‚Ή3 K
3 weeks
– / –
4 months

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 encounter problems that you to work with strings in...read more
Fibonacci Number
Fibonacci Number
In mathematics, we have different types of numbers like integers, natural, real, rational, etc. Along with these, we have a beautiful number with a remarkable property known as a Fibonacci...read more

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 integers, 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 Python split() function divides a string into a list of substrings based on a specified delimiter. By default, it splits by any whitespace and returns a list of words....read more
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 integers, 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 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 math.factorial() method to calculate and print the factorial of the number directly.
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. I hope this article helped you 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
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio