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

– / –
40 hours
– / –
5 days
– / –
3 days
β‚Ή3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks
– / –
3 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 Reverse a String in Python
Fibonacci Number

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 Join() Function
Methods to Check for Prime Numbers in Python

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
String Formatting in Python
Series vs. DataFrame in Pandas – Shiksha Online

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