Find factorial of a number in python : Python tutorial 25

Find factorial of a number using for loop , while loop and recursion in python :

What is factorial :

Factorial of a number is the multiplication of all the numbers from 1 to that number e.g. factorial of 3 is 1 * 2 * 3 i.e. 6 . To find factorial, we can either use loops or recursive approach. Following examples will explain you properly how to find factorial of a number in python :

Using for loop :

Using for loop we can iterate from 1 to that specific number we want to find out factorial . On each iteration , we will multiply the final result with current iteration count . final result will be 1 at first. So, after the loop will exit, we will get the factorial of that number .

def factorialUsingForLoop(n):
    fact = 1
    for i in range(1,n+1):
        print (i)
        fact=fact*i

    print('Factorial of the number %d is %d'%(n,fact))

if __name__== "__main__":
    factorialUsingForLoop(4)

Find factorial using while loop :

We can similarly find out the factorial of a number using a while loop. On each time , we will decrease the value of the number by 1 and multiply it with the final result.

def factorialUsingWhileLoop(n):
    fact = 1
    while(n>1):
        fact = fact*n
        n = n - 1

    print('Factorial is %d'%(fact))

if __name__== "__main__":
    factorialUsingWhileLoop(4)

Factorial using Recursion :

Recursion means the same function will be called recursively. To find factorial of a number, we can also use recursive approach like below :

def factorialUsingRecursion(n):
    if (n == 1):
        return 1
    else :
        return n* factorialUsingRecursion(n-1)

if __name__== "__main__":
    print "factorial is ",factorialUsingRecursion(4)

Leave a Reply