0% found this document useful (0 votes)
2 views2 pages

Recursion Explanation

Recursion in Python is a technique where a function calls itself to solve problems by breaking them into smaller, similar problems. Key components include a base case to stop recursion and a recursive case where the function calls itself. While recursion is useful, it may be less efficient than iterative solutions and has a default recursion limit of 1000.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Recursion Explanation

Recursion in Python is a technique where a function calls itself to solve problems by breaking them into smaller, similar problems. Key components include a base case to stop recursion and a recursive case where the function calls itself. While recursion is useful, it may be less efficient than iterative solutions and has a default recursion limit of 1000.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Recursion in Python: Explanation and Examples

Recursion in Python is a programming technique where a function calls itself in order to solve a

problem. Recursive functions are typically used to solve problems that can be divided into smaller,

similar problems.

Here's the general structure of a recursive function in Python:

1. Base Case: The condition under which the recursion stops.

2. Recursive Case: The part where the function calls itself.

Example: Factorial Calculation

def factorial(n):

# Base case

if n == 0 or n == 1:

return 1

# Recursive case

return n * factorial(n - 1)

# Test the function

print(factorial(5)) # Output: 120

How It Works:

- The base case stops the recursion when n is 0 or 1.

- For any other value of n, the function calls itself with a reduced argument (n - 1).

Example: Fibonacci Sequence


def fibonacci(n):

# Base case

if n <= 0:

return 0

elif n == 1:

return 1

# Recursive case

return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function

print(fibonacci(6)) # Output: 8

Key Points About Recursion:

1. Base Case: Ensure there is a base case to prevent infinite recursion.

2. Depth: Python has a recursion limit (default is 1000). Use sys.setrecursionlimit() if needed but

cautiously.

3. Performance: Recursive functions may be less efficient than iterative solutions for some problems

due to function call overhead.

Converting to Iteration:

For performance reasons, recursive solutions can sometimes be rewritten as iterative solutions. For

example, Fibonacci can be implemented using a loop for better efficiency.

You might also like