# Factorial Program in Python: Top 6 Methods

## What is factorial?

The factorial of a number(non-negative integers) is the product of all positive numbers that are less than or equal to the number itself. The factorial for negative numbers is not defined and for 0 it is 1(exception). It is denoted by !

Formula:
n! = n x (n-1) x (n-2) x (n-3) … 1

Examples:
1! => 1 => 1
2! => 2 x 1 => 2
3! => 3 x 2 x 1 => 6
4! => 4 x 3 x 2 x 1 => 24
5! => 5 x 4 x 3 x 2 x 1 => 120

We will find the factorial of a number in Python using 6 different methods. Let’s start

### Method 1: Using for loop

```n = int(input('Enter number: '))
factorial = 1
for i in range(1, n+1):
factorial = factorial * i
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {n} is {factorial}')```

### Method 2: Using while loop

```num = int(input('Enter number: '))
n = num
factorial = 1
while n >= 1:
factorial = factorial * n
n = n - 1
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {num} is {factorial}')```

### Method 3: With function using for loop

```def factorial(n):
num = 1
for i in range(1, n+1):
num = num * i
return num
n = int(input('Enter number: '))
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {n} is {factorial(n)}')```

### Method 4: With function using while loop

```def factorial(n):
num = 1
while n > 1:
num = num * n
n = n - 1
return num
n = int(input('Enter number: '))
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {n} is {factorial(n)}')```

### Method 5: With recursive function

```def factorial(n):
if n > 1:
return n * factorial(n-1)
return 1
n = int(input('Enter number: '))
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {n} is {factorial(n)}')```

### Method 6: Using in-built factorial() method of math module

```import math
n = int(input('Enter number: '))
print('Enter value greater than equal to 0' if n < 0 else f'Factorial of {n} is {math.factorial(n)}')```