Python Program to find the factorial of a Number : Python Tutorial 20

Python program to find the factorial of a number :

The factorial of a number is the product of all the numbers from 1 to that number. e.g. factorial of 5 is 1 * 2 * 3 * 4 * 5 i.e. 120 .

Factorial is denoted by “!” : 5 factorial is denoted by 5!

def fact(x):
     if x == 0 :
          return 1
return x * fact(x - 1)

print fact(5)
The output is “120

In the above example ,
  1. fact() function takes one argument “x
  2. If  “x ” is “0“,  it will return
  3. Else it will return x * fact(x-1) i.e. fact(x-1) will call fact() function one more time with (x-1) as argument . 
  4. It will continue till x is 0 , i.e. the function will return 1
So, for 5, 
  1. it will call 5 * fact (4) 
  2. fact(4 ) will be 4 * fact (3)
  3. fact(3) will be 3 * fact (2 )
  4. fact(2) will be 2 * fact (1)
  5. fact(1) will be 1 * fact (0)
  6. fact(0) is 1
  7. That means , the final output is 
5 * fact(4) 
= 5 * 4 * fact(3)
= 5 * 4 * 3 * fact(2)
= 5 * 4 * 3 * 2 * fact(1)
= 5 * 4 * 3 * 2 * 1 * fact(0)
= 5 * 4 * 3 * 2 * 1 * 1
= 120
Try changing the input number to different and check the result.

Leave a Reply