Factorial program in Python using function | Example code

  • by

You can use the math module factorial function to create your own Factorial program in Python using function. To create your own factorial function you have to use for loop.

factorial of 5 is

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

factorial of n is

n!=n*(n-1)*....2*1

Note: Factorial is not defined for negative numbers, and Factorial of zero(0) is: 1

Example of factorial program in Python using function

Simple example code finds factorial of a user-given number.

def find_factorial(n):
    f = 1
    for i in range(1, n + 1):
        f = f * i
    return f


x = int(input("Enter a number: "))

result = find_factorial(x)

print("Factorial is:", result)

Output:

Factorial program in Python using function

Use built-in function factorial() by importing math module

import math

x = 5

res = math.factorial(x)
print(res)

Output: 120

Do comment if you have any doubts or suggestions on this Python factorial code.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.