python

Factorial of a Number Using Recursion in Python

This python script asks the user to enter a number, and it finds its factorial using a recursive function. Factorial of a number is the product of the number by the smaller numbers, for example, the factorial of 4 is  4 * 3 * 2 * 1 = 24.
 

Factorial of a Number Using Recursion in Python

In this script, we have defined a factorial() function. This function takes a number as argument and finds its factorial.
 
[st_adsense]

def factorial(n):
    """This is a recursive function which
   calls itself to find the factorial of the given number """
    if n == 1:
        return n
    else:
        return n * factorial(n - 1)


# Asks the user to enter a number
n = int(input("Enter a number: "))

if n < 0:
    print("Factorial cannot be calculated for negative numbers!")
elif n == 0:
    print("Factorial of 0 is 1")
else:
    print("Factorial of", n, "is: ", factorial(n))

Output:

Enter a number: 3
Factorial of 3 is: 6
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *