Factorial(!) of a number (N) is the multiplication of all numbers from 1 to N. Formula is as defined below.
N! = 1 * 2 * 3 * 4 ... N # for example 4! = 1 * 2 * 3 * 4 = 24
In this article, we are going to write a python program (in all different ways) to find the factorial of the given number.
Factorial of a number in python using loops
# factorialnum.py # The function returns the factorial of given number. def factorial(num): if num < 1: return -1 fact = 1 # multiply all numbers from 2 to N. for i in range(2, num+1): fact = i * fact return fact # prints the factorial of 4. print(factorial(4))
In the above program, we are using for loop to multiply all numbers from 1 to N. The output of the above code is as shown below.
# Output $python factorialnum.py 24
We can even find the factorial numbers in python using a recursion function.
# Recursion function for factorial. F(N) = N * F(N-1)
Let’s write the python code to find factorial using recursion.
# factorialrecur.py # The function returns factorial using recursion. def factorialRecur(num): if(num < 2): return 1 return num * factorialRecur(num-1) # prints the factorial of 4. print(factorialRecur(4))
The output of the above code is as follows.
# Output $ python factorialrecur.py 24
These are the two methods to identify the factorial of any given number using python programming. Hope this article helps you to understand the factorial in python. Happy learning!!.