Factorial Programming in Python

Factorial Programming in Python

Code for Factorial Programming in Python

This is a simple program for Factorial Programming in Python.

print(">>> PROGRAM TO FIND FACTORIAL OF NUMBER USING FOR LOOP<<<\n")

# To take input from the user
num = int(input(">> Enter a number to find its factorial: "))
print("\n")

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print(">> Sorry, factorial does not exist for NEGATIVE NUMBERS")
elif num == 0:
   print(">> The factorial of 0 is: 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print(">> The factorial of",num,"is:",factorial)

Introduction to Factorial Programming in Python

We have come a long way, from covering the basic to most advanced topics and projects in Python. We have a dedicated series of detailed Python tutorials. Today, in this article, we will cover Introduction to Factorial Programming in Python, one of the most important programming concepts of all time, and also the favorite program that interviewers ask for. In situations involving higher mathematics and data analysis, the factorization of an integer is widely used. We will be covering different methods for coding Factorial Programming in Python and also some basics before getting started.

It is imperative to get a basic idea of What actually Factorial Programming in Python means? How it is done? What are the different methods and much more? So before starting let’s take a quick introduction to what the factorial of a number means and then we will start the actual coding for this program.

What is Factorial?

In simple words, a factorial is a number that is not negative. In other words, if a person wants to know What is the factorial of the number 6.? Then simply all you have to do is start multiplying 6 with all the numbers less than it (including 6). A number is multiplied by all the integers between 1 and the number itself to determine its factorial. It is denoted mathematically by the symbol “!“.

Mathematically it is stated that “A non-negative integer is a factorial. It is the multiplication of all positive integers that are less than or equal to the factorial you have requested”.

6! = 6 × 5 × 4 × 3 × 2 × 1
= 720
So the factorial of 6 is 720

Formula of factorial

n! = 1× 2 × 3 × 4 ×….× n

Here n is the positive number of which you want to find factorial.

With this concept clear in mind, it will be straightforward for you to code this in Python. Now let us take some examples to understand it in a better way.

Examples of Factorial of a Number

Example 1: Factorial of 10 (10!)

Answer:
10 ! = 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1
= 3628800

Example 2: Factorial of -2 (-2!)

Answer: Not defined

PLEASE NOTE:

  • There is no defined factorial for negative numbers.
  • Additionally, the factorial for the integer 0, or 0! is 1.

What does Factorial Programming in Python mean?

Factorial Programming in Python simply means that we have to find the factorial of the given number using Python. The change is that we have to implement this using Python. This basically means that we have to write a Python script that lets the user enter the number and in an answer, the script should return the factorial of that number.

To perform this task there are three methods i.e using for loop, using the Built-in function and last one is using Recursion. In both these methods, we will be using this formula that we learned at the start of this article. Let us understand both these methods with a detailed explanation.

Methods of Factorial Programming in Python

Factorial Program in Python using For loop

You can learn what is a for-loop in Python from our website, click here to learn now.

print(">>> PROGRAM TO FIND FACTORIAL OF NUMBER USING FOR LOOP<<<\n")

# To take input from the user
num = int(input(">> Enter a number to find its factorial: "))
print("\n")

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print(">> Sorry, factorial does not exist for NEGATIVE NUMBERS")
elif num == 0:
   print(">> The factorial of 0 is: 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print(">> The factorial of",num,"is:",factorial)

Output:

Introduction to Factorial Programming in Python For loop output
Output for Factorial Program in Python using for-loop

Explanation:
Line 1: Simple message about the program using print()
Line 2 to 3: To take the input from the user we used the input() function. And to convert the given input to an integer we used int(). This is one of the type conversion functions of Python. Now, this input is stored in the variable named num.
Line 4:
A variable named factorial is declared and it holds 1 as its default value.
Line 5 to 8: Now as we know, the negative number is not defined and the factorial of zero is 1. So to handle this situation. whenever the user enters 0 or a negative number particular message needs to be displayed.
For this,

  • We initiated a conditional loop (if) on line 5 and check whether the entered number by the user is less than zero or not. If the value inside the num variable is less than 0, then this message will be displayed “>> Sorry, factorial does not exist for NEGATIVE NUMBERS”
  • Now, if the number entered by the user is equal to 0, then we already know that the factorial of 0 is 1 and so we will return the following message “>> The factorial of 0 is 1”

Line 9: On line 9 we initiated an else block, this block is basically used to handle all the situations when the user neither enters a number less than 0 nor 0.
Line 10: Here we ran a for loop in between the range of 1 to num+1.
Line 11: factorial = factorial*i This is the main logic line of our code.
Decoding the loop and formula,

  • Here at first the value of factorial is 1
  • Now when we enter the for loop, initially the value of i=1, so the value that will be stored in factorial after this factorial = factorial*i will be factorial = 1*1
  • Now as the loop iterates, the value of i=2, so the value in factorial is, factorial = 1*2. Now the updated value of factorial is 2
  • This process goes on till the value of i=6 and then it terminates because the range function stops before the specified number and in our case, it is 7 so it will stop at 6

Line 12: Printing out the result.

Factorial of a number in Python using a Built-in function

This is the 2nd method in Factorial Programming in Python. And in this method, we will simply use the built-in function named factorial of math library.

To learn What is a function in Python? click here.

print(">>> PROGRAM TO FIND FACTORIAL OF NUMBER USING BUILT-IN FUNCTION <<<\n")

import math  
def fact(n):  
    return(math.factorial(n))  
  
num = int(input(">> Enter a number to find its factorial: "))  
print("\n")  

result = fact(num)  
print(">> The factorial of", num, "is", result)
print("\n\n") 

Output:

Introduction to Factorial Program in Python using built-in function
Output for Factorial Program in Python using the built-in function

Python program for Factorial of a number using Recursion

Before starting with this last method of Factorial Programming in Python, let’s take a loop at What is recursion in the programming world?

What is Recursion?

Python also permits function recursion, allowing defined functions to call one another. To put it plainly, it indicates that a function calls itself. This has the advantage of allowing you to loop through data to arrive at a conclusion.  Recursion eliminates the need for a loop but it needs to be used wisely.

Now let us understand the code of Factorial programming using Recursion

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""
    if x == 1:
        return 1
    else:
        # recursive call to the function
        return (x * factorial(x-1))

print(">>> PROGRAM TO FIND FACTORIAL OF NUMBER USING RECURSION <<<\n")

num = int(input(">> Enter a number to find its factorial: "))
print("\n")

# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)

Output:

Introduction to Factorial Programming in Python recursion output
Output for Factorial of a number in Python using recursion

Line 1 to 3: We declared a function named factorial that holds the logic of finding the factorial of a number, This function takes one input. On lines 2 and 3 we have placed the doc string of our function.
Line 4: We used an if block and the first condition that we check is that if the value of x is equal to 0 or 1, then we return 1
Line 5 to 6: It is an else block that process all other numbers except 0 and 1.
Decoding (x * factorial(x-1)),

  • Now initially the value of x=6 (As shown in the above output)
  • What (x * factorial(x-1)) line will do is that it will multiply 6 with the output of the factorial() function. So basically (6 * factorial(5)).
  • This factorial(5) will then again call the factorial function which means the flow of code will go to Line 10 and now it will be (6 * 5 * factorial(4)).
  • Now factorial(4)), will again call factorial with 4 as an argument. So it will be (6 * 5 * 4 * factorial(3))
  • This process will go on till 1 and then the condition x==1 is matched and so as per our code it will return 1
  • The final answer is then returned.

Line 7 to 9: A normal print message and an input taken in the same way as we took in Method 1 i.e Factorial programming using For loop.
Line 10: Calling our function named factorial() and also passing the parameter num. We will store the value it returns in the result variable.
Line 11: Printing out the result.

The only function that we used here is factorial() which is offered by the math library. This is an in-built function. It simply takes the number and in return, it gives the factorial of that number. This is the most basic and least time taking method of finding factorials.

Video Reference

Reference Links

Python Tutorial: Click here
Recursion in Python: Click here

Conclusion

Kudos !! We have finally mastered Factorial Programming in Python. In this article, we have tried to cover each and every method used for Factorial Programming. Starting from the most basic method to the most advanced method. We hope our detailed explanation of each method turned out to be useful to our readers and provided a great source of learning. We encourage our readers to try other different methods to find out the factorial of a number and drop your answers in the comment box. Till then try exploring new concepts, learn them, and try building on your own.

Thank you for visiting our website.


Also Read:

Share:

Author: Ayush Purawr