Write a Python Program to Find Factorial of a Number Using Function

Give an integer  to assign to a program you have to  find the factorial of an integer. Factorial is the number that we get by multiplying the number with numbers below it.

The factorial of 0 and 1 is considered as 1.  

The factorial of a negative number is not possible.

Using  you about statements let's write a program to evaluate the factorial of a number using python

 

 

Write a Python Program to Find Factorial of a Number Using Function



Write a Python Program to Find Factorial of a Number Using Function

Define a function, find_fact() take a number as an Input. Using if statement check the number is Equal to zero or equal to 1  it is true return factorial as 1.  Using else block take another variable product and initialize it to 1 using the for loop iterate from the range 2 to n + 1 and multiply the index with the product to get the factorial of number

def find_fact(n):
   if n == 0 or n == 1:
       return 1
   else:
       product = 1
       for index in range(2, n+1):
           product *= index
       return product
 
Once we find the product of all the numbers in the range, return the  product.




In the main program, take a variable named number use input() function and ask a user to enter a number and convert it into an integer.

Check if the number is less than 0 for a negative integer and print the appropriate error message, else if the number is greater than zero call the function and get the return value as a factorial of the number and finally print the factorial.

number = int(input("Enter a Number : "))
if number < 0:
   print("Factorial of Negative Number is Not Possible")
else:
   print(f"{number} Factorial is {find_fact(number)}")

 




Final program
================

def find_fact(n):
   if n == 0 or n == 1:
       return 1
   else:
       product = 1
       for index in range(2, n+1):
           product *= index
       return product

number = int(input("Enter a Number : "))
if number < 0:
   print("Factorial of Negative Number is Not Possible")
else:
   print(f"{number} Factorial is {find_fact(number)}")





Output
===============

Enter a Number : -20
Factorial of Negative Number is Not Possible




Output
============

Enter a Number : 5
5 Factorial is 120



Output
============

Enter a Number : 23
23 Factorial is 25852016738884976640000



Output
============

Enter a Number : 12
12 Factorial is 479001600



Conclusion
=================

Try providing the bigger integer as input to the Python program and running it see the difference.



Post a Comment

0 Comments