# Python Program to Find the Factorial of a Number

In this article, we will learn to find the factorial of a number using python program.

#### What is factorial?

In mathematics, the factorial of a non-negative integer n is the product of all positive integers less than or equal to n. The factorial of n also equals the product of n with the next smaller factorial.

n! = n x (n-1) x (n-2) x (n-3) x ....x 3 x 2 x 1

#### For example,

4! = 4 x 3 x 2 x 1 = 24

Now, using python we find the factorial of any number using 3 methods.

### Using loops

Using the loop we find the factorial of the number. Factorial of number is equal to the product of 1 to that number.

For example,

5! = 1 x 2 x 3 x 4 x 5 = 120

#### Program

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20``` ```# python program to find the factorial of number using for loop # take any number assigned it in variable named n n = 5 # if n is negative integer then the factorial is not exits if n<0: print("Factorial of negative number not possible") # factorial of 0 is 1 elif n == 0: print("Factorial of 0 is 1") else: # iterate the for loop from 1 to n factorial = 1 for i in range(1,n+1): # multiple the n with 1*2*3*...*n factorial = factorial*i # print the factorial of n print("Factorial of",n,"is",factorial) ```

#### Output

Factorial of 5 is 120

### Using Recursion

Using recursion we find the factorial of a number by making a function named factorial that calls itself.

#### Program

 ``` 1 2 3 4 5 6 7 8 9 10 11 12``` ```# python program to find the factorial of number using Recursion # make a function named factorial def factorial(n): if (n==1 or n==0): return 1 else: # call the function again until the n ==1 or n ==0 return(n * factorial(n - 1)) n = 5 # call the function print("Factorial of",n,"is",factorial(n)) ```

#### Output

Factorial of 5 is 120

### Using built-in function

factorial() is a in built function. To use factorial function we have to import math.

#### Program

 ```1 2 3 4 5 6``` ```# python program to find the factorial of number using factorial() function # import math import math n = 5 # use the math.factorial() function to find the factorial of any number print("Factorial of",n,"is",math.factorial(n)) ```

#### Output

Factorial of 5 is 120

No Comment