Factorial Program in Python

Hi, in this article  let's learn a Factorial program in Python. The factorial of a number is  defined as the product of the number and the number below it.  

The problem statement is we need to write a Python program asking a user to enter a number and find the factorial of the number and print it.
 
 
 
factorial program in python

 

 
For example let's say take a number 5

we want to find the 5 factorial  then it is denoted by 5! (Exclamation Mark).

5 ! =  5 x 4 x 3 x 2 x 1 = 120

You should also very best condition may have 0 factorial is equals to 1 




With that understood let's try to write a Factorial program in Python

Let's ask a user to enter a number and then convert it into an integer then try to find the factorial of a number using a for loop and print it.

number = int(input("Enter a number : "))
product = 1

if number < 0:
   print("Factorial of negative number is void")
   exit(-1)
elif number == 0 or number == 1:
   product = 1
elif number > 1:
   for index in range(2, number+1):
       product = product * index

print("Factorial of a Number is :", product)



Now let's try to solve Factorial program in Python using while loop

Take a while loop and initialize the index and travels from 0 to that number and multiply the product as we are doing the same in above  for loop program

number = int(input("Enter a number : "))
product = 1

if number < 0:
   print("Factorial of negative number is void")
   exit(-1)
elif number == 0 or number == 1:
   product = 1
elif number > 1:
   index = 2
   while index < number+1:
       product = product * index
       index += 1

print("Factorial of a Number is :", product)



Now let's try to solve Factorial program in Python using Recursion

Recursion is a method where a function calls itself directly or indirectly. Let's use a recursive function to find the factorial of a number by calling it until the number reduces to one and keep finding the product of the numbers below it.


def find_factorial(n):
   if n == 0 or n == 1:
       return 1
   else:
       return n * find_factorial(n - 1)


number = int(input("Enter a number : "))

if number < 0:
   print("Factorial of negative number is void")
   exit(-1)
else:
   product = find_factorial(number)

print("Factorial of a Number is :", product)



Call the recursive function after validating the number is greater than 0 and get the factorial of a number and print it in the main program.


OUTPUT 1 :


Enter a number : 2
Factorial of a Number is : 2


OUTPUT 2 :

Enter a number : -5
Factorial of negative number is void


OUTPUT 3 :

Enter a number : 12
Factorial of a Number is : 479001600


OUTPUT 4 : Factorial of 8
 
Enter a number : 8
Factorial of a Number is : 40320 

 
OUTPUT 5 : Factorial of 4
 
Enter a number : 4
Factorial of a Number is : 24

 
 
Keywords : Factorial Program in Python, factorial of 8, factorial of 4, write a program to find factorial of a number in python

Post a Comment

0 Comments