Python Recursion

What is Recursion?

Recursion occurs when a function calls itself to solve smaller instances of a problem. It is often used to solve tasks that can be broken down into repetitive sub-tasks, such as factorial calculations or traversing hierarchical data structures.




Tutorials dojo strip

Why Use Recursion?

Recursion simplifies tasks that involve repetitive sub-problems like calculating a factorial or counting residents in nested lists of barangays. It can replace complex loops with simpler function calls for some algorithms.




Syntax

Define a base case to stop recursion, and include a recursive call that moves toward this base case.

def recursive_function(parameters):
    if base_condition:
        return result
    else:
        return recursive_function(modified_parameters)




Example

# Function to calculate factorial of a number using recursion
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Calculate factorial of 5, often used for barangay event permutations
print("Factorial of 5:", factorial(5))  # Output: 120




Python Labs

Tutorials dojo strip
Scroll to Top