Python Program to Find the Factorial of a Number

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

  1. Using for loop
  2. Using Recursion
  3. Using math.factorial() method
  4. Using reduce() Function

One thing to remember is that the factorial of both 0! and 1! is 1. You can’t calculate the factorial of a negative number.

Visual Representation of Python Program to Find the Factorial of a Number

Method 1: Using for loop

You can use a for loop to iterate from number 1 up to the designated number, multiplying at each step.

Example

number = 6 # number = int(input("Enter a number: "))

factorial = 1

# Checking if the number is negative, zero, or positive
if number < 0: 
 print("Factorial cannot be calculated for negative numbers")
elif number == 0 or number == 1:
 print(1)
else:
 for i in range(1, number + 1):
  factorial = factorial * i
 print("Factorial of", number, "is:", factorial)

Output

Factorial of 6 is : 720

Method 2: Using Recursion

The recursive function calls itself with decreasing values of number until it reaches 1.

Example

def factorial_recursive(number):
 if number < 0:
  print("Factorial cannot be calculated for negative numbers")
 elif number == 0 or number == 1:
  return 1
 else:
  return number * factorial_recursive(number - 1)

# Call the factorial function and print the result
print("Factorial of 6 is : ", factorial_recursive(6)) 

Output

Factorial of 6 is: 720 

Method 3: Using math.factorial() method

The factorial() method from the math module returns the factorial of a given non-negative integer.

Visual Representation

Visual Representation of Using math.factorial() method

Example

import math

number = 6

if(number < 0):
 print("Factorial cannot be calculated for negative numbers")
else:
 print("Factorial of", number, "is:", math.factorial(number))

Output

Factorial of 6 is: 720

Method 4: Using reduce() Function

The reduce function applies the lambda function (which multiplies two numbers) cumulatively to the items, effectively calculating the product of all numbers from 1 to n.

Example

from functools import reduce

def factorial_reduce(number):
 if number < 0:
  return "Factorial cannot be calculated for negative numbers"
 return reduce(lambda x, y: x*y, range(1, number+1)) if number > 0 else 1

print("Factorial of 6 is :", factorial_reduce(6))

Output

Factorial of 6 is: 720

That’s it.

Leave a Comment

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