Factorial of a number using userdefined function in Python

In this tutorial, we will learn how to find the factorial of a given number without using the inbuilt function i.e math.factorial() in Python.
Python providing a fantastic set of libraries which are very useful and makes the work much easier, But here is the catch, we will learn to do it without the inbuilt function.

Factorials have a wide range of applications in the field of mathematics, such as Permutations and Combinations.

Before diving in let us know what factorial is with an example,

What is Factorial?

Factorial of a number n  is defined as the multiplication of the number 1 to the number n. It is denoted by the symbol ! .
n! – 1 x 2 x 3 x …… x n-1 x n.
example:
6! – 1 x 2 x 3 x 4 x 5 x 6 – 720
5! – 1 x 2 x 3 x 4 x 5 – 120
12! = 1 x 2 x 3 x …… x 11 x 12 =479001600

Code: user-defined function to get factorial of a number in Python

def fact(n):
    if n == 0 or n ==1 :
        return 1
    else:
        return (n * fact(n-1))
        

n = 5
print(fact(n))

The value of n can be changed according to the requirements of the user.
we can make the program menu-driven by taking the input from the user. This makes the program more dynamic and keeps the user involved in the process.

def fact(n):
      if n == 0 or n ==1 :
        return 1 
      else:
        return (n * fact(n-1))
n = input("enter any number from 0-100")
print(fact(n))

Output:

enter any number from 0-100
5
120

The above code asks the user to enter a number and calculates its factorial.

The user-defined function from the math module i.e factorial() used in place of this. It takes the value of n as a parameter and gives the same output as above.

Leave a Reply

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