Skip to content

Write a Python function to calculate the factorial of a number | Code

  • by

A simple way to write a Python function to calculate the factorial of a number is using an if-else statement and for-loop. Where The factorial of a number is the product of all the integers from 1 to that number.

Python function to calculate the factorial of a number

A simple example code to get the factorial of 6 is 1*2*3*4*5*6 = 720.

Note: Factorial is not defined for negative numbers, and the factorial of zero is one, 0! = 1.

num = 6

# To take input from the user
# num = int(input("Enter a number: "))

factorial = 1

if num < 0:
    print("Enter Positive number")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial = factorial * i
    print("The factorial of", num, "is", factorial)

Output:

Write a Python function to calculate the factorial of a number
iterationfactorial*i (returned value)
i = 11 * 1 = 1
i = 21 * 2 = 2
i = 32 * 3 = 6
i = 46 * 4 = 24
i = 524 * 5 = 120
i = 6120 * 6 = 720

Using In-built function:

The math module has a factorial() function to find the factorial of any number.

import math

num = 5
res = math.factorial(num)

print("Factorial:", res)

Output: Factorial: 120

Recursive method

def factorial(n):
    # single line to find factorial
    return 1 if (n == 1 or n == 0) else n * factorial(n - 1);


num = 5
print(factorial(num))

Output: 120

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

Note: IDE: PyCharm 2021.3.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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading