Python Program to Find the Factorial of a Number

Here are three ways to find the factorial of a number in Python.

  1. Using “for loop”
  2. Using “recursion”
  3. Using “math.factorial()” method

Method 1: Using for loop

You can use a “for loop” to iterate through number 1 till the designated number and keep multiplying at each step.

num = input("Enter a number: ")

factorial = 1
if int(num) >= 1:
  for i in range(1, int(num)+1):
    factorial = factorial * i
  print("Factorial of ", num, " is : ", factorial)

Output

Enter a number: 4
Factorial of 4 is : 24

Method 2: Using recursion

A recursive function is a function that calls itself during its execution. This enables the function to be repeated several times, as it can call itself during its execution.

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

print(factorial(4))

Output

Factorial of 4 is: 24

Method 3: Using math.factorial() method

To calculate the factorial of a number in Python, you can use the built-in “math.factorial()” method.

Syntax

math.factorial(num)

Parameters

num: It is an integer. If we provide float or any negative number, it will throw an error.

Return Value

The “factorial()” method returns the factorial of the desired number.

Example 1

# Taking input from user
num = int(input("Enter the number to find factorial: "))

# Declaring one temporary variable to store the answer
fact = 1

# Finding factorial of the given number
for i in range(1, num+1):
  fact = fact*i

print("Factorial of the given number ", num, " is: ", fact)

Output

Enter the number to find factorial: 5

Factorial of the given number 5 is: 120

Example 2: If the given number is Negative

import math

num = input("Enter a number: ")
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))

Output

ValueError: factorial() not defined for negative values

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.