Computer >> Computer tutorials >  >> Programming >> Python

Calculate Factorial in Python


Suppose we have a number n less than or equal to 10, we have to find its factorial. We know that the factorial of a number n is n! = n * (n - 1) * (n - 2) * ... * 1.

So, if the input is like 6, then the output will be 720

To solve this, we will follow these steps −

  • Define a function solve(). This will take n
    • if n <= 1, then
      • return 1
  • return n * solve(n - 1)

Let us see the following implementation to get better understanding −

Example

class Solution:
   def solve(self, n):
      if(n <= 1): return 1
         return n * self.solve(n - 1)
ob = Solution()
print(ob.solve(6))

Input

6

Output

720