factorial() in Python


Finding the factorial of a number is a frequent requirement in data analysis and other mathematical analysis involving python. The factorial is always found for a positive integer by multiplying all the integers starting from 1 till the given number. There can be three approaches to find this as shown below.

Using a For Loop

We can use a for loop to iterate through number 1 till the designated number and keep multiplying at each step. In the below program we ask the user to enter the number and convert the input to an integer before using it in the loop. This way we ensure we get positive integers in the calculation.

Example

 Live Demo

n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
for i in range (1,int(n)+1):
   factorial = factorial * i
print("Factorail of ",n , " is : ",factorial)

Output

Running the above code gives us the following result −

Enter a number: 5
Factorail of 5 is : 120

Using Recurssion

Example

 Live Demo

num = input("Enter a number: ")
def recur_factorial(n):
if n == 1:
   return n
elif n < 1:
   return ("NA")
else:
   return n*recur_factorial(n-1)
print (recur_factorial(int(num)))

Output

Running the above code gives us the following result −

#Run1:
Enter a number: 5
120
#Run2:
Enter a number: -2
NA

Using math.factorial()

In this case we can directly use factorial function which is available in math module. We need not write the code for factorial functionality rather directly use the math.factorial(). That also takes care of negative numbers and fractional numbers scenario.

Example

 Live Demo

import math
num = input("Enter a number: ")
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))

Outputs

Running the above code gives us the following result −

#Run1:
Enter a number: 5
The factorial of 5 is :
120
#Run 2:
Enter a number: 3.6
Traceback (most recent call last):
The factorial of 3.6 is :
File "C:/Users....py", line 5, in
print(math.factorial(int(num)))
ValueError: invalid literal for int() with base 10: '3.6'

Updated on: 23-Aug-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements