Trusted answers to developer questions

Educative Answers Team

The **factorial(!)** of a number **n** is the product of all positive numbers less than or equal to n.

The factorial of a number is defined as:

$factorial(n)=n * factorial(n-1)$

$or$

$factorial(n)=n * (n-1) * (n-2) ... * 1$

Note:The factorial of 0 is 1.

To calculate the factorial of 4, have a look at the following illustration:

$4 != 4*3*2*1$

In Python, there are two approaches to computing the factorial of a number:

- Iterative Method
- Recursive Method

The following code explains how to compute the factorial of a number using the iterative approach:

def factorial(n): fact = 1 for num in range(2, n + 1): fact *= num return fact

The iterative approach works by setting a base value to $1$. For each loop, the method multiplies to the base value until the `for`

loop finishes and you get the final factorial value.

The recursive approach is when the function calls itself again and again until some stopping condition. It has two parts:

This is where the recursion stops

This is the case where the function calls itself again and again until the base condition is reached.

$factorial(4)=4*factorial(3)$

$factorial(3)=3*factorial(2)$

$factorial(2)=2*factorial(1)$

$factorial(1)=1*factorial(0)$

The following illustration explains how to compute the factorial of a number using recursion in Python:

def factorial(n): if n == 1: #base case return n else: return n*factorial(n-1) # recursive case number = 4 if number < 0: print("Factorial exists for positive numbers only") elif number == 0: print("Factorial of 0 : 1") else: print("Factorial of",number,":",factorial(number))

RELATED TAGS

factorial

python

Copyright Â©2022 Educative, Inc. All rights reserved

RELATED COURSES

View all Courses

Keep Exploring

Related Courses