Friday, August 26, 2022

Python Program to Find Factorial of a Number

In this post we’ll see how to write a Python program to find factorial of a number.

Factorial of a non-negative integer n is product of all positive integers from 1 to n. For example factorial of 4 can be calculated as-

4! = 4 X 3 X 2 X 1 = 24

Factorial program is one of the first program you'll write to understand recursive function so naturally in this post you'll see python program for factorial using recursion apart from writing using its iterative counterpart.

There is also an inbuilt function in Python for calculating factorial.

1. Recursive program to find factorial. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of factorial program that base case is when num is 1.

def factorial(num):
  # base case(exit recursion)
  if num == 0 or num == 1:
    return 1
  else:
    return num * factorial(num - 1);

num = int(input('Enter a number- '))
print(factorial(num))

Output

Enter a number- 6
720

2. Iterative program to find factorial. Here for loop is used to iterate the passed number until it becomes 1, decrementing by 1 in each pass.

def factorial(num):
  fact = 1
  if num < 0:
    print('Please enter non-negative number')
  else:
    for i in range(num, 1, -1):
      fact = fact * i
    print('Factorial is- ', fact)

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- -4
Please enter non-negative number

Enter a number- 0
Factorial is-  1

Enter a number- 4
Factorial is-  24

3. Using factorial function of the math module in Python. Import math module and use math.factorial() function to find factorial of a number.

import math

def factorial(num):
  print('Factorial is- ', math.factorial(num))

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- 7
Factorial is-  5040

That's all for this topic Python Program to Find Factorial of a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Fibonacci Series
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Python return Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Class And Object in Python
  3. Removing Spaces From String in Python
  4. Fibonacci Series Program in Java
  5. Buffered Streams in Java IO
  6. DatabaseMetaData Interface in Java-JDBC
  7. Array in Java With Examples
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial