In this python program, we will find the factorial of a number. We are going to use the for loop. We have also used the range() function to traverse through every number between 1 and num+1.
Note:- In range() function the numbers which are included are the numbers in between the range defined plus the lower limit but the upper limit is not included.
Eg:- In range(1,5) only 1,2,3,4 numbers are included.
In this program, there will be a loop which goes from value 1 to num+1 and keep multiplying that value with variable fac and store back to variable fac. And when the loop is finished it's going to output the variable fac which will be the factorial of the variable num.
Code for finding factorial of a number using python
# taking input from user
num = int(input("Enter a number: "))
# initializing the initial value of fac
fac = 1
# running for loop
for i in range(1,num+1):
fac = fac * i # multiplying previous fac value to i and store it back in fac variable
print("The factorial of the number is ",fac) # printing the factorial of number
Output:-
Enter a number: 5
The factorial of the number is 120
There is one more way of finding the factorial of a number using the recursion.
Recursion is a function which calls itself one or more times in its body. Recursion is mainly used to breaking down the problems into sub-problems.
Finding the factorial of a number using the recursion
In this method, we create a function(recursive function) which will take variable num as the argument. Inside the function, there will be two cases.
First one is the base case, which returns value 1 whenever the value of num becomes less than equal to 0. And the second case is the iterative case which will return the product of num and return value of fac(num-1).
Code:
# defining the recursive function for finding factorial
def fac(num):
if num <= 0:
# Base case
return 1
else:
# Iterative case
return num * fac(num-1)
# Taking input from user
num = int(input("Enter a number:"))
#printing the factorial of the number by calling fac function
print("The factorial of the number is",fac(num))
Now you know about the range() function and also about the recursive functions, so you can use these functions to make some new programs.