Write a Python Program to Find Factorial of a Number Using Recursion

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Find Factorial Of A Number Using Recursion

 

Title : 

Write A Python Program To Find Factorial Of A Number Using Recursion



Write a Python Program to Find Factorial of a Number Using Recursion


 

Description : 

Hey guys in this article you will learn How to find the factorial of a number using the recursion. Note : this program is only limited to 999 recursions only, if you want to attend this recursion limit then you have to modify your computer environment. Define a function named as a factorial of N by passing and integer as input to it. Use the if statement to check if the value of n is equals to zero or equals to 1 then return the value as 1. Use the else block to keep multiplying n and calling the factorial function by reducing value of n by 1.


    
def factorial(n):
   if n == 0 or n == 1:
       return 1
   else:
       return n * factorial(n - 1)



    


In the main program aaj ke user to enter a number and store it into num variable


    

num = int(input("Enter a non-negative integer: "))


    


Use and if statement to check if the number is less than 0 then print the negative error message factorial of a negative number is not defined Use the else block to print the factorial of a number by calling the above recursive factorial function.


    

if num < 0:
   print("Factorial is not defined for negative integers")
else:
   print(f"Factorial of a number {num} is : {factorial(num)}")


    




Complete Python Code : 


    
def factorial(n):
   if n == 0:
       return 1
   else:
       return n * factorial(n - 1)


num = int(input("Enter a non-negative integer: "))

if num < 0:
   print("Factorial is not defined for negative integers")
else:
   print(f"Factorial of a number {num} is : {factorial(num)}")

    

 

 

Output : 


    
Enter a non-negative integer: 12
Factorial of a number 12 is : 479001600


    

 

Output : 


    
Enter a non-negative integer: 1
Factorial of a number 1 is : 1


Enter a non-negative integer: 0
Factorial of a number 0 is : 1


Enter a non-negative integer: -12
Factorial is not defined for negative integers


    



Conclusion :

The above Python program prompts the user to Enter non negative number and call the recursive function. The recursive factorial function keeps calling itself until the value of n is zero or one. Comment it down below if you have any suggestions to improve the above Python program

 

Post a Comment

0 Comments