How to find Factorial of a number in Python

Hello Programmers, In this blog post you will learn to find the Factorial of a number in Python. Factorial is the multiplication of all the numbers before the number till 1 and the number itself. It’s very easy to find the factorial of a number in Python. Let us learn about it in detail:- 

Factorial of a number in python

Factorial of  Numbers 

0! = 1 

1! = 1

2! = 2 * 1 = 2

3! = 3 * 2 * 1 = 6

4! = 4 * 3  * 2 * 1 = 24 

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

Way to find Factorial of a number in python:-

In this code, we have taken n as input from the user to get the value of the number whose factorial users want to find. Then we will declare the value of fact as 1 because we will use it afterward. Now we will use a loop because a user can enter any number wheater its positive, Negative, or Zero.

 

So in the first case of the loop when a user enters a negative number or number < 0 then the output will be Factorial if this number cannot be found. In the second case where the number is equal to 0, we will give its value 1 because the factorial of 0 is 1. 

 

Now in the third and last case where the number is greater than 1, we will start a loop from the range 1 to n+1 numbers and will apply the formula factorial = factorial * I Which is used to find the factorial of a number. Now we can print and you will get a factorial of that particular number.

Factorial.py

 
n = int (input ( “Enter a Value to find Factorial: “ ))
 
fact = 1
 
if n < 0:
    print( “Factorial of this Number Cannot be found “)
elif n == 0:
    print( “Factorial of 0 is 1 “)
else:
    for i in range (1, n+1):
        fact = fact * i
    print( “The factorial of”,n,“is: “,fact)
 

OUTPUT

Case 1:- 

Enter a Value to find Factorial: 0
Factorial of 0 is 1

Case 2:- 

Enter a Value to find Factorial: -1
Factorial of this Number Cannot be found

Case 3:-

Enter a Value to find Factorial: 5
The factorial of 5 is: 120

Case 4:- 

Enter a Value to find Factorial: a
Traceback (most recent call last):
File “d:\factorial.py”, line 1, in <module>
n = int (input ( “Enter a Value to find Factorial: ” ))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: ‘a’

 

It will show an error in this case beacuse we have given a as input. So it will not accept it as a is a alphabet and we have already declared that in n only integer can be written because we want only numbers to operate this code. 

Hope this blog post was helpful to you and you have got the answer to your question. Thank you for visiting our blog. If you have any doubts about any coding questions then let us know in the comments section we will answer them as soon as possible. Till then check out our more blog posts.

Leave a Comment

Your email address will not be published. Required fields are marked *