Python | Find factorial of a given number

In this tutorial, we will learn how to find the factorial of a given number using Python program? By IncludeHelp Last updated : January 05, 2024

Factorial Example in Python

Given a number and we have to find its factorial in Python.

Example:

Input:
Num = 4

Output:
Factorial of 4 is: 24

Different methos to find factorial of a number

There are mainly two methods by which we can find the factorial of a given number. They are:

  1. Find factorial using Loop
  2. Find factorial using Recursion

1. Find factorial using Loop

# Code to find factorial on num

# number
num = 4

# 'fact' - variable to store factorial
fact = 1

# run loop from 1 to num
# multiply the numbers from 1 to num
# and, assign it to fact variable

for i in range(1, num + 1):
    fact = fact * i

# print the factorial
print("Factorial of {0} is: {1} ".format(num, fact))

Output

The output of the above program is:

Factorial of 4 is: 24

2. Find factorial using Recursion

To find the factorial, fact() function is written in the program. This function will take number (num) as an argument and return the factorial of the number.

# function to calculate the factorial
def fact(n):
    if n == 0:
        return 1
    return n * fact(n - 1)

# Main code
num = 4

# Factorial
print("Factorial of {0} is: {1} ".format(num, fact(num)))

Output

The output of the above program is:

Factorial of 4 is: 24 

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.