What’s up all! Welcome again to Technifyed I’m Vasav here and in this blog, you’ll get to know how to get the factorial of a number in Python!
We can derive the factorial in two ways namely the logical way or idly the longer one & the shorter one derived using modules. First, we’ll look at the logical way. I’m naming the first method logical as in that method we’re going to apply our own brains and solve with the help of modules.
I know that I’ve already wasted a lot of your time soo, are we ready? I’m sure yes!
Here we go:
def factorial_logic(num):
We’ve added def as we have started a function next we’ve written the name of the function and lastly, num is the variable.
ans = 1
Here we have defined a variable named as and assigned the value 1 to it.
if num == 0: return ans
We’re telling python if the number is 0 then return the 1 as the answer.
else: for a in range (num): ans *= a + 1 return ans
Python has been ordered that if the number is not zero then find all the numbers before the given number and multiply them all and add one or simply calculate the factorial and return the number.
Input example:
factorial_logic(6)
Output
720
Till now we’ve learned a long way to solve this problem. Now let’s take a look at the shorter and easier way now.
import math def factorial_module(num): return math.factorial(num)
So simple!
Also Read:
How to make a Profit Calculator using Python
Python Variables the Storage Place
Find the Missing Number in Two Different Ways Using Python