factorial program in python

In this post, we will see how to find factorial of a number in python.
Factorial of number is product of all integer from 1 to that number.
For example:
Factorial of 4 is : 1*2*3*4=24
There are two ways to do it.

  • Using iteration
  • Using recursion

Using iteration

Here is simple python program to find factorial of a given number.

num=4 #uncomment below line to take input from user #num =int(input("Enter number:")) factorial=1 while(num!=0): factorial*=num num=num-1 print(factorial)

Output:

24

Explanation:

  • Intialize facorial to 1
  • Iterate until num is not equal to zero
  • Multiply number by factorial by num and decrement the num.

Using Recursion

You can find factorial of the program using recursion as well.

# Python program to find the factorial of a number using recursion def factorial(num): if(num == 1): return num else: return num*factorial(num-1) num=4 #uncomment below line to take input from user #num =int(input("Enter number:")) print(factorial(num))

Output:

24

That’s all about finding factorial of given number in java.

Leave a Reply

Your email address will not be published. Required fields are marked *