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?
For example,
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
Using Recursion
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
Using built-in function
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)) |