SoFunction
Updated on 2024-11-15

Detailed explanation of several ways to calculate factorial with python

The first one: using the functools tool to process

import functools
result = (lambda k: (int.__mul__, range(1, k + 1), 1))(5)
print(result)

Second: Normal Loop

x = 1
y = int(input("Please enter the number to be calculated:"))
for i in range(1, y + 1):
  x = x * i
print(x)

The third one: using recursion

def func(n):
  if n == 0 or n == 1:
    return 1
  else:
    return (n * func(n - 1))


a = func(5)
print(a)

Each of the above three approaches takes a different approach, with the second being the easiest to understand, the first being the most pythonic, and the third being the easiest to use. The third one directly defines a factorial function that can be called at any time to get different values.

I hope this will help you in your studies and I hope you will support me more.