Factorial Program in python using recursion with explanation

calculate the factorial using recursion

In this tutorial, we are going to learn writing python program to find the factorial of the number using recursion method. We will take a number from the users as and input and our program will print the factorial as an output.

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.

What is recursion?

Recursion is a method that defines something in terms of itself, which means it is a process in which a function calls itself. A complete function can be split down into various sub-parts in recursion. It makes code look simple and compact. It is also defined as the process of defining a program or problem in terms of itself.

Let’s have a look at the simple diagram that explains the working of recursion.

factorial program in python using recursion

Our logic to find factorial of a number using recursion

  • 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 fact(num) user-defined recursive function that will return the factorial of the given number i.e. num.

Let’s understand through a diagram how our recursive function will work on input 7.

Algorithm to find factorial of a number using recursion

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 7: Stop

Python Program to find factorial of a number using recursion

Output 1:

factorial program using recursion in python

Explanation:

factorial program using recursion in python

Output 2:

python factorial program using recursion

Explanation:

python factorial program using recursion