Python – Factorial of a Number

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

Examples

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 = 4
result = factorial(n)
print(n,'! = ',result,sep="")
Run Code Copy

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

4! = 24

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 to find factorial of a number n
def factorial(n):
    if n < 0:
        print('Invalid number to find factorial.')
    elif n==1 or n==0 :
        return 1
    else :
        return n * factorial(n - 1);  

# Take a number
n = 10

# Call recursion function
result = factorial(n)

# Print result
print(result)
Run Code Copy

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

# Take a number
n = 5

# Calculate factorial
result = factorial(n)

print(result)
Run Code Copy

Summary

In this tutorial of Python General Programs, we learned different ways to write a Python Program to compute factorial of a given number.

Related Tutorials

Code copied to clipboard successfully 👍