Python Program to Find the factorial of a number
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.
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
The factorial of the number is 120
There is one more way of finding the factorial of a number using the recursion.
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).
# 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.
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019