Python Tutorials

Python Programs

Python Find Factorial of a Number using Recursion


Python Find Factorial of a Number using Recursion

In this tutorial, we will learn how to find the factorial of a number using recursion in Python. We will cover the basic concept of recursion and implement a recursive function to calculate the factorial.


What is Recursion

Recursion is a programming technique where a function calls itself in order to solve smaller instances of the same problem. It is particularly useful for problems that can be broken down into smaller, similar sub-problems.


Syntax

The syntax to find the factorial of a number using recursion in Python is:

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


Youtube Learning Video



Finding the factorial of a number using recursion

We can create a recursive function to calculate the factorial of a given number.

For example,

  1. Define a function named factorial that takes one parameter n.
  2. Check if n is equal to 0. If true, return 1 (base case).
  3. Otherwise, return n multiplied by the result of calling factorial with n - 1 (recursive case).
  4. Call the function with a sample number and print the result.

Python Program

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

# Find the factorial of 5
result = factorial(5)

# Print the result
print('Factorial of 5 is', result)

Output

Factorial of 5 is 120