Python Program - Find Factorial of a Number
The factorial of a positive integer is the multiplication of all positive integer less than or equal to that number.
factorial of number n = n! = n(n-1)(n-2)...1
For Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
4! = 4 × 3 × 2 × 1 = 24
Method 1: Using Recursive method
In the example below, a recursive function called factorial() is used to calculate factorial of a number.
def factorial(x): if x == 0 or x ==1: return 1 else: return x*factorial(x-1) print("10! = ", factorial(10)) print("6! = ", factorial(6))
The above code will give the following output:
10! = 3628800 6! = 720
Method 2: Using Iterative method
The factorial of a number can also be calculated using iterative method.
def factorial(x): final = 1 for i in range(x,1,-1): final = final * i return final print("10! = ", factorial(10)) print("6! = ", factorial(6))
The above code will give the following output:
10! = 3628800 6! = 720
Method 3: Using Short-hand If-else method (Ternary operator)
In the example below, the factorial of a number is calculated using short-hand if-else method.
def factorial(x): y = 1 if (x == 0 or x ==1) else x * factorial(x-1) return y print("10! = ", factorial(10)) print("6! = ", factorial(6))
The above code will give the following output:
10! = 3628800 6! = 720
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle