Factorial of any number N using recursion

Recursion is a property of function where it can call itself. Recursion is only available to a few programming languages like C, C++, and Python.

Factorial of any number n is equal to its multiplication of  1x2x3 upto n-1x n. There are two methods to find out factorial of n. 1

  1. Using Looping method
  2. Using recursion

1. Factorial of Number N using Looping

Looping means repeatation-Python support only two type of loops- while loop and for loop.

#   program to find out factorial of any number n using looping method
#made by        : rakesh kumar

n = int(input('Enter any number n: '))
fact = 1
for i in range(1, n+1):
    fact *= i

print('Factorial of {} is {}'.format(n, fact))

Other programs written using for loops are as follows

Factorial of any number N using recursion

Since in this case we are bound to call our user-defined function in order to find out the factorial of our input number N. Here is the code for computing factorial of integer number N.

def factorial(n):
    if n==1:
        return 1
        return n*(factorial(n-1))

#function call 
n = int(input("Enter any number "))
result = factorial(n)
print("factorial of {} is  {} ".format(n,result))

The output of the above program is as follows

rakesh@folio MINGW64 /e/python (master)
$ python -u "e:\python\Loops\factorial.py"
Enter any number n: 4
Factorial of 4 is 24

Recursion is an integral part of dynamic programming. This question is a part of the practical assignments of class 12 python students.  You can download a sample list of practical assignments for class 12 computer science students. here.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.