A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/recursion-in-python/ below:

Recursion in Python - GeeksforGeeks

Recursion in Python

Last Updated : 03 Jun, 2025

Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.

In Python, a recursive function is defined like any other function, but it includes a call to itself. The syntax and structure of a recursive function follow the typical function definition in Python, with the addition of one or more conditions that lead to the function calling itself.

Basic Example of Recursion: Python
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  

Explanation: The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. The recursive approach involves the function calling itself with a decremented value of n until it reaches the base case of 1.

Let's understand recursion in python deeply:

Basic Structure of Recursive Function

def recursive_function(parameters):

if base_case_condition:

return base_result

else:

return recursive_function(modified_parameters)

Base Case and Recursive Case

Example:

Python
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))  

Explanation:

Types of Recursion in Python

Recursion can be broadly classified into two types: tail recursion and non-tail recursion. The main difference between them is related to what happens after the recursive call.

Here is a Python example that demonstrates both tail recursion and non-tail recursion:

Python
def tail_fact(n, acc=1):
    # Base case
    if n == 0:
        return acc
    # Tail recursive call with an accumulator
    else:
        return tail_fact(n-1, acc * n)

def nontail_fact(n):
    # Base case
    if n == 1:
        return 1
    # Non-tail recursive call because the multiplication happens after the call
    else:
        return n * nontail_fact(n-1)

# Example usage
print(tail_fact(5))  
print(nontail_fact(5))  
Recursion vs Iteration Recursion: Iteration: Advantages of using recursion Disadvantages of using recursion
Introduction of Recursion Application's of Recursion Writing base case in Recursion

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4