Contents
Python Program to Find Factorial of a Number
Factorial of a Number can be calculated in many ways. Some of them are by using a for loop, or using a recursion function or a while loop.
In the following Python Factorial Examples, we will find factorial of a given whole number, using the above said procedures.
Problem Statement – Factorial of a Number
Factorial of a number n is given by,
n! = n*(n-1)*(n-2)*...3*2*1
For example,
0! = 1
1! = 1
2! = 2*1 = 2
3! = 3*2*1 = 6
4! = 4*3*2*1 = 24
Run You have to read n from user through console input. And print the answer to the console.
Example 1: Factorial using For Loop and Range
In the following example, we shall use Python For Loop to find Factorial. For a range(1,n+1) of given n, multiply the element over each iteration and return the result after coming out of the loop.
Python Program
def factorial(n):
result = 1
for i in range(1,n+1):
result = result*i
return result
n = int(input('Enter a number: '))
result = factorial(n)
print(n,'! = ',result,sep="")
We have not validated if the number is negative. You may write the validation to check if the number is not negative and then proceed with finding the factorial.
Output
C:\python>python factorial.py
Enter a number: 4
4! = 24
C:\python>python factorial.py
Enter a number: 6
6! = 720
C:\python>python factorial.py
Enter a number: 12
12! = 479001600
Example 2: Factorial using Recursive Function
Recursive functions are popular among budding programmers. But when it comes to performance, recursion is not a preferable choice in Python.
Python Program
#recursion function
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1);
#read input from user
n = int(input('Enter a number: '))
#call recursion function
result = factorial(n)
#print result
print(result)
Example 3: Factorial using While Loop
We shall use Python While Loop in this solution of finding factorial of a number.
Python Program
#function computes factorial of a given number
def factorial(n):
result = 1
i=1
while i<=n:
result*=i
i+=1
return result
#read input from user
n = int(input('Enter a number: '))
#calculate factorial
result = factorial(n)
print(result)
Summary
In this tutorial of Python Examples, we learned different ways to write a Python Program to compute factorial of a given number.