Python Program to Find the Factorial of a Number


This content was proof-read by Grammarly. You can Try Grammary for FREE

In this Python program, you will learn how to find the factorial of a number and display it using the print statement.

Before we start coding, its important to understand what is a factorial. The factorial of a number is the product io all the number from 1 until that number.


Are you a .NET Developer planning to integrate GraphQL for .NET in your Application? Check out this book

To give you an example , lets say you want to find the factorial of 4. You can find it by multiplying 4 * 3 * 2 * 1.

The usual formula is

N*(N-1) where N is a decrementing values until 1.

How to find the factorial of a number in Python?

# Author : Abundantcode.com
# Python Program to find the factorial of a number provided

input = 4
fact = 1

# find if the number is negative
if input < 0:
   print("Invalid number")
elif input == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,input + 1):
       fact = fact*i
   print("The factorial of",input,"is",fact)

Output

The factorial of 4 is 24

In the above program, the number for which we want to find the factorial is stored in the variable input. We perform the following steps to find if the factorial of the number.

  1. Check if the Number is Negative and show appropriate message.
  2. If the input is 0 , display the result as 1
  3. Use for loop to find the factorial.
%d bloggers like this: