Python Program for Factorial

Python Factorial of n is that the product of all positive descending integers. Factorial of n is denoted by n!.

Python Program for Factorial Using Loop and Recursive Function
Image by Speedy McVroom from Pixabay

Here, 4! is pronounced as “4 factorial”, it is also called “4 bang” or “4 shriek”.

The factorial is normally used in Combinations and Permutations (mathematics).

To understand this example, you should have knowledge of following Python programming topics:

There are many ways to write down, let’s have a look at the two ways in which to write down the factorial program in Python.

  • Factorial Program using the loop
  • Factorial Program using recursion

Source Code: Factorial Using Loop in Python

In this program, we are taking input from the user. Then using for loop we are calculating factorial and printing the value.

num = int(input("Enter a number: "))
fact = 1

for i in range(1,num+1):
   fact = fact * i 

print("Factorial of ",num, "is :",fact)

Source Code: Factorial Using Recursive Function in Python

In this python program, we are using recursion. We have created a function called fact_recur(). In that function, we are using if else and in else we use a recursive function.

# Factorial using Recursion 
# StudyGyaan.com

def fact_recur(n):
   if n==0:
      return 1
   else:
      return(n*fact_recur(n-1))

num = 4
print("Factorial of",num,"is",fact_recur(num))
Python Factorial Program Video Tutorial

It’s also available on GitHub: https://github.com/studygyaan/python-tutorial/blob/master/python-factorial.py