Python Program To Calculate The Factorial

Description

                   In this tutorial, we are going to learn a python program to find the factorial of the number given as input from the user.

Problem Statement

                   For any numbers that are input by the user, we have to calculate the factorial of that numbers.

For example

            Case1: If the user input the 5.

                        then the output should be 120 ( 1*2*3*4*5= 120).

            Case2: If the user input the 6.

                        then the output should be 720 (1*2*3*4*5*6 =720).

What is Factorial of a number?

                   The factorial of a number is the multiplication of each and every number till the given number except 0.

For example

Case 1: factorial of number 4 is the multiplication of every number till number 4, i.e.  1*2*3*4

Case 2: factorial of number 3 is the multiplication of every number till number 3, i.e.  1*2*3

Note

  • The factorial of 0 is 1
  • The factorial of any negative number is not defined.
  • The factorial only exits for whole numbers.

Our logic to find factorial

  • Our program will take an integer input from the user which should be a whole number.
  • If the number input is negative then print ‘The factorial can’t be calculated’.
  • Then use for loop with range function to define the sequence of numbers which we will use to calculate the factorial.
  • After that, we will store the value of the factorial in a variable and finally print the value of the variable.

Algorithm of Factorial Program In Python

Step 1: Start

Step 2: take input from the user for finding the factorial.

 Step 3: Create a variable ‘factorial’ and assign the value 1.

Step 4: if(number<0):

               print ‘cannot be calculated.

           elif ( number == 1):

            print 1

           else:

            for i in range(1, number+1):

                   factorial*=i 

Step 5: print factorial

Step 6: Stop

Let’s code the above algorithm in the python programming language.

Python program to calculate the factorial

#taking an integer input from user
num=int(input("Enter the whole number to find the factorial: "))
factorial = 1
if num &lt; 0:
   print("Factorial can't be calculated for negative number")
elif num == 0:
   print("Factorial of 0 is 1")
else:
#calculating the factorial of the input number
   for i in range(1,num + 1):
       factorial = factorial*i
print("Factorial of",num,"is",factorial)

Output 1:

Explanation of the above factorial output

                   The input number from the user to find the factorial is 5. The calculated value of the factorial is 1*2*3*4*5.

Output 2:

Explanation of the above factorial output

The input number from the user to find the factorial is 8. The calculated value of the factorial is 1*2*3*4*5*6*7*8.


[wpusb]