SoFunction
Updated on 2025-03-06

Four ways to write factorials in Python

Factorials –>> Mathematics use n! = n*(n-1)(n-2)(n-3)…321, the factorials of 0 are also 1. I cannot interpret them, so I can only start simply from 1.

The first type: derivation formula + loop through the multiplication of each element in the list

def factorial(n):
    li =[i for i in range(1,n+1)]   #li = [1,2,3,4] Derivation formula, forming a list, starting from 1 to ending n+1 (closing left and opening right, n must +1)    a = 1                           # a = 1 starts to calculate. If starting from 0, any integer 0× is 0, it doesn't make much sense to this question    for i in li:                    # traverse elements in the list. The loop needs to be traversed before proceeding to the next step        a = a *i                  # = The a on the left is the assignment multiplied by the right. The first time = the right is 1*1, then a =1, the second time = the right is 1*2, then = the left a=2, the third time = the right is 2*3, then = the left a=6,.......    return a
print(factorial(4)) 

The second type: cumulative calculation of calling functools module reduce

from functools import reduce  #reduce cumulative calculation, format is reduce (function, sequence) sequence: array list, tuple, dictionarydef factorial(n):
    li = [i for i in range(1,n+1)]   #Same as the first derivation formula to form a list    return reduce((lambda x,y:x*y),li)  # Anonymous function lambdaprint(factorial(4))

The third type: recursion

def factorial(n):
    if n <=1:
        return 1
    return n*factorial(n-1)
print(factorial(5))

The fourth type: prod in module numpy

import numpy
def func(n):
    Array = [i for i in range(1,n+1)]
    return (Array)
print(func(1))

This is the end of this article about the six ways to write factorials in Python. For more related Python factorial content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!