Python | Factorial of a number using Recursion

Using the concept of recursion, we have two methods to solve this problem. Let us take a look at that method.

Method 1: Using factorial

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

num = int(input("Enter a number whose factorial you want: "))  

if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   print("The factorial of",num,"is",get_factorial(num))

Output:

Enter a number whose factorial you want: 5
The factorial of 5 is 120

Enter a number whose factorial you want: -1
Opps!, The number you entered is negative. Factorial does not exist for negative numbers

Explanation:

The concept of finding factorial is quite similar to that of finding Fibonacci. Here we simply took the input from the user and passed on that to the function. The main idea of the factorial of a particular number is to reduce the number by 1 and multiply all of them until 1. So using for loop we reduced n each time in the loop until the value of n comes down to 1. At the same time, the value computed is stored and multiplied by the value computed by the next for loop.

Method 2: Using a one-liner if statement

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

num = int(input("Enter a number whose factorial you want: "))  

if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   print("The factorial of",num,"is",get_factorial(num))  

Explanation:

The approach is the same as the above method but the only difference is that here we used a one-liner if statement and nothing else.

We hope this article was helpful in some ways.

Share:

Author: Dhvanil V