DEV Community

Max
Max

Posted on

Python Recursion Function Tutorial

Recursion is a technique in programming where a function calls itself repeatedly until a certain condition is met. Recursion is an important concept in many programming languages, including Python.

How Recursion Works

Recursion works by breaking down a problem into smaller subproblems until a base case is reached. The base case is a condition that, once met, stops the recursion and returns a value.

Each recursive call makes progress toward the base case by reducing the problem to a smaller size. Eventually, the problem becomes small enough to solve directly, and the function returns a value that is used to solve the larger problem.

Find Factorial Of a Number Recursion In Python

A classic example of recursion is the calculation of a factorial. A factorial is the product of all positive integers up to a given number.
For example, the factorial of 4 is 4 x 3 x 2 x 1 = 24.

The factorial function can be defined recursively as follows:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
Enter fullscreen mode Exit fullscreen mode

In this function, we check if the input parameter n is equal to 0. If it is, we return 1, as the factorial of 0 is 1. If n is not 0, we return n multiplied by the factorial of n - 1.

Let's test this function with some sample inputs:

print(factorial(0)) # 1
print(factorial(5)) # 120
print(factorial(10)) # 3628800
Enter fullscreen mode Exit fullscreen mode

Output:

1
120
3628800
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

Python Lambda Function Tutorial
Python If, If-Else Statements Tutorial
Python Function Tutorial
Python break and continue tutorial
Python While Loop tutorial

Top comments (0)