Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a List
This article is about finding factorial of any number in Python. In mathematics, a factorial is a positive number and represented as n!. A factorial is a product of all positive integers less than or equal to n.
For example, if we calculate the factorial of 3, then the product of all integers less than 6 will be 3*2*1 = 6. It means the factorial of 3 is 6.
Now, let's implements it using the Python program.
Step 1: Take a number
Step 2: Check whether the number is greater than 1
Step 3: Iterate a loop for all the values less than the number
Step 4: Calculate factorial
Step 5: Repeat step 3 and 4 until the loop exits
Step 6: Display factorial
This algorithm is to calculate the factorial without using math.factorial() method. You can see its implementation in example2 below.
Python provides a math module that contains the factorial() method. We can use this method to calculate factorial for any number as we did in the below code example.
import math
# Take a number
num = 5
print(num)
fact = 1
# Find factorial
fact = math.factorial(num)
# Display result
print("Factorial is: ",fact)
Output:
5
Factorial is: 120
In this example, we are using for loop to calculate the factorial of a number. We can use this code if don't want to use math.factorial() method. See the code and output.
# Take a number
num = 5
print(num)
fact = 1
# Find factorial
if num >= 1:
for i in range (1, num+1):
fact = fact * i
# Display result
print("Factorial is: ",fact)
Output:
5
Factorial is: 120
Recursion is a technique in which a function calls itself until the base condition. Here, we used the recursion approach to find a factorial of a number in Python. See the code and output.
# Take a number
num = 5
print(num)
fact = 1
# Find factorial
def factorial(num):
if num < 2:
return 1
else:
return num * factorial(num-1)
# Display result
print("Factorial is: ",factorial(num))
Output:
5
Factorial is: 120