Learnitweb

Python Program for factorial of a number

In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:

n! = n × ( n − 1 ) × ( n − 2 ) × ( n − 3 ) × ⋯ × 3 × 2 × 1

For example,

5 ! = 5 × 4 × 3 × 2 × 1 = 120

Note: factorial is defined only for non-negative integer numbers.

Finding factorial of a number in Python using Iteration

1. Factorial of a number using for loop

# input number to calculate factorial
num = int(input("Enter the number :"))
 
#initialize factorial to 1
factorial = 1

if num < 0:
    print("Factorial is defined only for non-negative integer numbers")
else:
    for i in range(1,num+1):
        factorial = factorial * i
    print("Factorial of {} is {}".format(num, factorial))

Output

Enter the number :5
Factorial of 5 is 120

2. Factorial of a number using while loop

def factorial(number):
    if number == 0 or number == 1: 
        return 1
    else: 
        factorial = 1
        while(number > 1): 
            factorial = factorial * number 
            number = number - 1
        return factorial

#input number to calculate factorial
number = int(input("Enter the number :"))

#calculate factorial if number is non-negative
if number < 0:
    print('Factorial is defined only for non-negative integer numbers')
else:
    print('Factorial is ', factorial(number))

Factorial of a number using recursion

def factorial(number):
    return 1 if (number==1 or number==0) else number * factorial(number - 1)  
	
#input number to calculate factorial
number = int(input("Enter the number :")) 
print("Factorial is", factorial(number))

Factorial of a number using in-built math module

from math import factorial
 
num = int(input("Enter the number :"))
 
fact = factorial(num)
 
if num < 0:
    print("Factorial is defined only for non-negative integer numbers")
else:
    print("Factorial is", factorial(num))