Python program to find factorial of a number

In this article, we will study the famous problem python program to find the factorial of a number. The factorial of a number is the product of all integers from 1 to that number. Many companies like Wipro, Accenture, TCS, and many more asked these types of questions in their technical interviews for checking a candidate’s fundamental knowledge. Let’s discuss the different methods to find the python program to find factorial of a number.

Example:
Enter the number: 5

Output:
A factorial of 5 is 120

Explanation:
5! Will be 5 x 4 x 3 x 2 x 1, that is 120

Algorithm to find python program to find factorial of a number.

  1. Get a positive integer input (n) from the user.
  2. Iterate from 1 to n using a for loop (for loop is used to increment the number up to the given input)
  3. Using the below formula, calculate the factorial of a numberf = f*i.
  4. Print the output i.e the calculated factorial

Method 1: python program to find factorial of a number using factorial() function.

Code Implementation:

n = int (input ("Enter a number: "))
factorial = 1
if n >= 1:
    for i in range (1, n+1):
    	factorial=factorial *i
print("Factorial of the given number is: ", factorial)

Output: The factorial of 5 is 120

Method 2: Python program to find factorial of a number using for loop.

Code Implementation:

n = int (input ("Enter a number: "))
factorial = 1
if n >= 1:
    for i in range (1, n+1):
    	factorial=factorial *i
print("Factorial of the given number is: ", factorial)

Output: The factorial of 5 is 120

Method 3: Python program to find factorial of a number using recursion.

Code Implementation:

# Factorial of a number using recursion
def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 5

# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

Output: The factorial of 5 is 120

Conclusion:

In this blog, we have discussed the different approaches to finding the python program to find factorial of a number. We hope this article will help you to clear all your doubts and build your confidence. PrepBytes provides you with the best content also you may check our MYCODE platform to check where you actually stand as these questions are prepared by our expert mentors.

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to add two numbers
Python program to find the middle of a linked list using only one traversal
Python program to reverse a linked list

Leave a Reply

Your email address will not be published. Required fields are marked *