ComputerShikshak.com

Python - Factorial of a Number

Problem Statement

Write a program in Python to find the Factorial of an integer number entered by the user.

Brief Description

According to the problem statement we have to write a program in Python that will take an integer value as input from the user through the keyboard and will find the factorial of that number.

Factorial of a number is obtained by multiplying all the integer values from 1 to that that number.

Also note the following two important points in order to find the factorial of a number:
(i) Factorial is not defined for the negative numbers.
(ii) Factorial of 0 is 1 i.e. 0!=1.

For example, if the user enters 5 as input, the program will generate 120 as output since 5!=1*2*3*4*5=120.

To view Flowchart click the link given below:

Flowchart – Factorial of a Number

Program

				
					num=int(input("Enter a number: "))
if num<0:
    print("Factorial is not defined for the negative numbers")
else:
    fact=1
    for i in range(1,num+1):
        fact=fact*i    #OR fact*=i
    print("Factorial of",num,"is",fact)
				
			

Output

Explanation

In this program:
  • 3 variables namely num, fact and i are used.
  • The integer value entered by the user is stored in num.
  • If a negative number is entered by the user, the condition num<0 is evaluated to True and the message “Factorial is not defined for the negative numbers” is displayed.
  • If a number which is greater than or equal to zero is entered, the condition num<0 is evaluated to False and control goes to the else block and the statements written within else block are executed.
The step-by-step working of the for loop (when num contains 5) is shown in the table given below:
numfact=fact*ifactiComment
5-----11Initial Values
5fact=1*112Iteration 1
5fact=1*223Iteration 2
5fact=2*364Iteration 3
5fact=6*4245Iteration 4
5fact=24*5120-----Iteration 5
While executing the for loop:
  • At first 1 is stored in fact.
  • After that 1 is stored in i.
  • The value of i is checked with respect to the stop value i.e. num+1.
    • If value of i is less than num+1, the statement written within for loop is executed and the loop continues to iterate till value of i is less than num+1. 
    • If value of i becomes equal to num+1 then the loop stops working and the control goes to the statement written immediately after the loop.
  • At the end of each iteration, the value of i is incremented by 1.
  • Within for loop, the value obtained in i is multiplied with the value stored in fact and the result is stored in the same variable i.e. fact.

Thus the above process generates the Factorial of the given number by multiplying all the integer values from 1 to that number. 

The final result is stored in fact. 

Finally the result is displayed on the output screen.

Share this page on
Scroll to Top