In the Python example series, we will discuss the Python Factorial Program.
What is factorial of a number?
First understand what is factorial of a number. Factorial of number n is the multiplication of n with its previous number up to 1 like
n*(n-1) *(n-2) *(n-3) …*1
e.g. if n is 5 then factorial of 5 will be 5*4*3*2*1 which is 120.
Some point to remember about factorial
- 0 factorial is 1
- 1 factorial is also 1
Let’s understand factorial program by example
# Python factorial example # 0! is 1 # 1! is 1 n=input("Enter the number:") n=int(n) #check whether number is 0 or 1 f=1 if n==0 or n==1 : print("factorial of", n,"is:", f) else : for i in range(1,n + 1): f = f*i print("The factorial of",n,"is",f)
Enter the number:5 The factorial of 5 is 120
- In above example, we ask the user to enter the number.
- We check whether entered number is 0 or 1, if number is 0 or 1, factorial of number will be 1, as we know that factorial of 0 and 1 is 1.
- If number is not 0 or 1, then program will go into else part.
- In else part, for i in range (1, n + 1), we have range function which will start from 1 and go to n+1 i.e. 6, as range function will take the number between 1 to 6. i.e. 1 to 5, so for loop will start from 1 and run till 5.
- In the next step, f = f*I, we are multiply current number with previous calculated number.
- At the end, we print the factorial of number.