Python Program to find factorial of a number

In this tutorial we will learn how to write Python program to find factorial of a number.

Formula to Calculate Factorial of a Number:

n! = 1 * 2 *3 . . . . . . n

OR

n! = n * ( n-1 ) * ( n – 2 ) . . . . . * 1

Factorial of 9 = 1*2*3*4*5*6*7*8*9 = 362880

Python program to find factorial of a number using Recursion :

def fact(num):
    
    if (num==1 or num==0):
        
        return 1 
    else:
        return num * fact(num - 1)
 
n = int(input("Enter number to Find Factorial: "))

factorial=fact(n)

print("Factorial of",n,"is",factorial)

Output :

Enter number to Find Factorial: 9
Factorial of 9 is 362880

Explanation :

n = int(input(“Enter number to Find Factorial: “))

Get user input and store it in variable n.

factorial=fact(n)

Call factorial function with user input as argument and store it in variable factorial.

 def fact(num):
    
    if (num==1 or num==0):
        
        return 1 
    else:
        return num * fact(num - 1)

Here definition of fact function, first we check if user input is 1 or 0 . If so return 1. If user input is other than 1 or 0 then call recursion function fact(num -1).

print(“Factorial of”,n,”is”,factorial)

At last print the factorial of user input number.

Program to find factorial in python using for Loop :

num = int(input("Enter number for factorial : "))

fact = 1

if num < 0:
    
   print("No  factorial for negative numbers")
   
elif num == 0:
    
   print("The factorial of 0 is 1")
   
else:
    
   for i in range(1,num + 1):
       
       fact = fact*i
       
   print("The factorial of",num,"is",fact)
   
   

Python program to find factorial using While Loop :

number = int(input(" Enter a Number to find factorial : "))
fact = 1
num = number
if number <0:
    print("No factorial for negative number")
else:
 while( number > 0):
    fact = fact * number
    number = number - 1

 print("The factorial of %d  = %d" %(num, fact))

Output :

 Enter a Number to find factorial : 5
The factorial of 5  = 120

Factorial using math function in Python:

import math

def factorial(n):
    
    return(math.factorial(n))
 
number = int(input("Enter number to find Factorial: "))

print("Factorial of", number, "is",factorial(number))
Share This!