Write a Python Program to Find Factorial of Number Using Recursion

In this tutorial, we will learn how to find the factorial of a number using recursion in Python programming language.

Factorial is a mathematical function denoted by an exclamation mark (!).

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

For example, the factorial of 5 (5!) is 54321 = 120.


Using Recursion

Recursion is a programming technique where a function calls itself repeatedly until a base case is reached.

A base case is a condition where the function stops calling itself and returns a value.

In this case, we can use recursion to find the factorial of a number by calling the function itself with a smaller number until we reach the base case where the number is 1.

Python Program

Let’s write a Python program to find the factorial of a number using recursion.

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

# Test the function
num = int(input("Enter a non-negative integer: "))
if num < 0:
    print("Factorial undefined for negative numbers.")
else:
    print("Factorial of", num, "is", factorial(num))

Explanation

The program defines a function called factorial that takes a single argument n, which represents the number whose factorial is to be calculated.

The function first checks if n is equal to 1, which is the base case.

If n is 1, the function returns 1, as 1! is equal to 1.

If n is not 1, the function multiplies n with the factorial of n-1, which is calculated by calling the factorial function recursively with the argument n-1.

This process continues until the base case is reached, where the function returns 1.

The program then prompts the user to enter a non-negative integer and checks if the number is negative.

If the number is negative, the program prints a message stating that the factorial is undefined for negative numbers.

If the number is non-negative, the program calls the factorial function with the entered number as the argument and prints the result.


Conclusion

In this tutorial, we learned how to find the factorial of a number using recursion in Python.

Recursion is a powerful technique that can simplify complex problems by breaking them down into smaller subproblems.

It is important to choose the base case carefully to avoid infinite recursion.

By understanding recursion, we can become better programmers and solve complex problems more effectively.